<?php

/**
 * Admin changelog model
 *
 * @package     Nails
 * @subpackage  module-admin
 * @category    Model
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Admin\Model;

use Nails\Common\Model\Base;
use Nails\Factory;

class ChangeLog extends Base
{
    /**
     * The chnages which are to be saved
     *
     * @var array
     */
    protected $aChanges;

    /**
     * Whether to save as a batch
     *
     * @var bool
     */
    protected $bBatchSave;

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

    /**
     * ChangeLog constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->table      = NAILS_DB_PREFIX . 'admin_changelog';
        $this->aChanges   = [];
        $this->bBatchSave = true;

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

        /**
         * Add a hook for after the controller is done so we can process the changes
         * and save to the DB.
         */
        $aHook = [
            'classref' => &$this,
            'method'   => 'save',
            'params'   => [],
        ];

        if (get_instance()->hooks->addHook('post_system', $aHook) === false) {
            $this->bBatchSave = false;
            Factory::service('Logger')
                ->line(get_class() . ' could not set the post_system hook to save items in batches.');
        }
    }

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

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

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

    /**
     * Save the changelog items
     *
     * @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();
    }

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

    /**
     * Clear all recorded changes
     */
    public function clear()
    {
        $this->aChanges = [];
    }

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

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

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

    /**
     * Applies common conditionals
     *
     * @param array $aData Data passed from the calling method
     *
     * @throws \Nails\Common\Exception\FactoryException
     **/
    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);
    }

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

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


<?php

namespace Nails\Admin\Api\Controller;

use Nails\Api\Controller\CrudController;
use Nails\Api\Exception\ApiException;
use Nails\Api\Factory\ApiResponse;
use Nails\Common\Exception\FactoryException;
use Nails\Factory;

class Note extends CrudController
{
    const REQUIRE_AUTH          = true;
    const CONFIG_MODEL_NAME     = 'Note';
    const CONFIG_MODEL_PROVIDER = 'nails/module-admin';
    const CONFIG_LOOKUP_DATA    = ['expand' => ['created_by']];

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

    /**
     * Determines whether the user is authenticated or not
     *
     * @param string $sHttpMethod The HTTP Method protocol being used
     * @param string $sMethod     The controller method being executed
     *
     * @return bool
     */
    public static function isAuthenticated($sHttpMethod = '', $sMethod = '')
    {
        return parent::isAuthenticated($sHttpMethod, $sMethod) && isAdmin();
    }

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

    /**
     * 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
     */
    public function getRemap($sMethod, array $aData = [])
    {
        list($sModel, $iItemId) = $this->getModelClassAndId();
        $aData['where'] = [
            ['model', $sModel],
            ['item_id', $iItemId],
        ];

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

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

    /**
     * Counts the number of items for a specific model/item combination
     *
     * @param array $aData Any data to apply to the requests
     *
     * @return ApiResponse
     * @throws ApiException
     * @throws FactoryException
     */
    public function getCount(array $aData = [])
    {
        list($sModel, $iItemId) = $this->getModelClassAndId();
        $aData['where'] = [
            ['model', $sModel],
            ['item_id', $iItemId],
        ];

        return Factory::factory('ApiResponse', 'nails/module-api')
                      ->setData($this->oModel->countAll($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
     */
    protected function validateUserInput($aData, $oItem = null)
    {
        $aData = parent::validateUserInput($aData, $oItem);

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

        return $aData;
    }

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

    /**
     * Returns an arry of the model's class name and the item's ID
     *
     * @return array
     * @throws ApiException
     * @throws FactoryException
     */
    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];
    }

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

    /**
     * Formats the response object
     *
     * @param \stdClass $oObj The object to format
     *
     * @return \stdClass
     */
    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,
            ],
        ];
    }
}


<?php

namespace donatj;

/**
 * Simple Calendar
 *
 * @author Jesse G. Donat <donatj@gmail.com>
 * @link http://donatstudios.com
 * @license http://opensource.org/licenses/mit-license.php
 *
 */
class SimpleCalendar {

	/**
	 * Array of Week Day Names
	 *
	 * @var array|false
	 */
	public $wday_names = false;

	private $now;
	private $dailyHtml = array();
	private $offset = 0;

	/**
	 * Constructor - Calls the setDate function
	 *
	 * @see setDate
	 * @param null|string $date_string
	 */
	public function __construct( $date_string = null ) {
		$this->setDate($date_string);
	}

	/**
	 * 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 setDate( $date_string = null ) {
		if( $date_string ) {
			$this->now = getdate(strtotime($date_string));
		} else {
			$this->now = getdate();
		}
	}

	/**
	 * 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 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++;
	}

	/**
	 * Clear all daily events for the calendar
	 */
	public function clearDailyHtml() { $this->dailyHtml = array(); }

	/**
	 * 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 function setStartOfWeek( $offset ) {
		if( is_int($offset) ) {
			$this->offset = $offset % 7;
		} else {
			$this->offset = date('N', strtotime($offset)) % 7;
		}
	}

	/**
	 * Returns/Outputs the Calendar
	 *
	 * @param bool $echo Whether to echo resulting calendar
	 * @return string HTML of the Calendar
	 */
	public function show( $echo = true ) {
		if( $this->wday_names ) {
			$wdays = $this->wday_names;
		} else {
			$today = (86400 * (date("N")));
			$wdays = array();
			for( $i = 0; $i < 7; $i++ ) {
				$wdays[] = strftime('%a', time() - $today + ($i * 86400));
			}
		}

		$this->arrayRotate($wdays, $this->offset);
		$wday    = date('N', mktime(0, 0, 1, $this->now['mon'], 1, $this->now['year'])) - $this->offset;
		$no_days = cal_days_in_month(CAL_GREGORIAN, $this->now['mon'], $this->now['year']);

		$out = '

';

		for( $i = 0; $i < 7; $i++ ) {
			$out .= '' . $wdays[$i] . '	';
		}

		$out .= "

\n
\n
";

		$wday = ($wday + 7) % 7;

		if( $wday == 7 ) {
			$wday = 0;
		} else {
			$out .= str_repeat(' 	', $wday);
		}

		$count = $wday + 1;
		for( $i = 1; $i <= $no_days; $i++ ) {
			$out .= 'now['mday'] && $this->now['mon'] == date('n') && $this->now['year'] == date('Y') ? ' class="today"' : '') . '>';

			$datetime = mktime(0, 0, 1, $this->now['mon'], $i, $this->now['year']);

			$out .= '<time datetime="' . date('Y-m-d', $datetime) . '">' . $i . '</time>';

			$dHtml_arr = false;
			if( isset($this->dailyHtml[$this->now['year']][$this->now['mon']][$i]) ) {
				$dHtml_arr = $this->dailyHtml[$this->now['year']][$this->now['mon']][$i];
			}

			if( is_array($dHtml_arr) ) {
				foreach( $dHtml_arr as $dHtml ) {
					$out .= '
' . $dHtml . '
';
				}
			}

			$out .= "	";

			if( $count > 6 ) {
				$out .= "
\n" . ($i < $no_days ? '
' : '');
				$count = 0;
			}
			$count++;
		}
		$out .= ( $count != 1 ) ? str_repeat(' 	', 8 - $count) . '
' : '';
		$out .= "\n

\n";
		if( $echo ) {
			echo $out;
		}

		return $out;
	}

	/**
	 * @param array $data
	 * @param int $steps
	 */
	private function arrayRotate( array &$data, $steps ) {
		$count = count($data);
		if( $steps < 0 ) {
			$steps = $count + $steps;
		}
		$steps = $steps % $count;
		for( $i = 0; $i < $steps; $i++ ) {
			array_push($data, array_shift($data));
		}
	}
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Workdiary API
 *
 * @final
 * @package     UpworkAPI
 * @since       05/19/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Workdiary API
 *
 * @link http://developers.upwork.com/Work-Diary
 */
final class Workdiary extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get Workdiary
     *
     * @param   string $company Company ID
     * @param   string $date Date
     * @param   array $params (Optional) Parameters
     * @return  object
     */
    public function get($company, $date, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/team/v3/workdiaries/companies/' . $company . '/' . $date, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get Workdiary by Contract
     *
     * @param   string $contract Contract ID
     * @param   string $date Date
     * @param   array $params (Optional) Parameters
     * @return  object
     */
    public function getByContract($contract, $date, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/team/v3/workdiaries/contracts/' . $contract . '/' . $date, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       04/21/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API;

use Upwork\API\Config as ApiConfig;

/**
 * Debug class
 */
class Debug
{
    /**
     * @var Debug status
     */
    static private $_debug = false;

    /**
     * Print debug message
     *
     * @param   string $str Debug message
     * @param   array $args (Optional) Value to dump
     * @static
     * @access  public
     * @return  void
     */
    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);
        }
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Metadata
 *
 * @final
 * @package     UpworkAPI
 * @since       05/15/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Metadata
 *
 * @link http://developers.upwork.com/w/page/49177378/Metadata%20API
 */
final class Metadata extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get Categories (v2)
     *
     * @return object
     */
    public function getCategoriesV2()
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/profiles/v2/metadata/categories');
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get Skills
     *
     * @return object
     */
    public function getSkills()
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/profiles/v1/metadata/skills');
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get regions
     *
     * @return object
     */
    public function getRegions()
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/profiles/v1/metadata/regions');
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get tests
     *
     * @return object
     */
    public function getTests()
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/profiles/v1/metadata/tests');
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get reasons
     *
     * @param   array $params Parameters
     * @return  object
     */
    public function getReasons($params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Contracts
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Contracts API
 *
 * @link http://developers.upwork.com/w/page/46842954/Contracts%20API
 */
final class Contracts extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Suspend Contract
     *
     * @param   integer $reference Contract reference
     * @param   array $params Parameters
     * @return  object
     */
    public function suspendContract($reference, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Restart Contract
     *
     * @param   integer $reference Contract reference
     * @param   array $params Parameters
     * @return  object
     */
    public function restartContract($reference, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * End Contract
     *
     * @param   integer $reference Contract reference
     * @param   array $params Parameters
     * @return  object
     */
    public function endContract($reference, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }
}


<?php
/**
 * Abstract Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       05/20/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\AuthTypes;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Config as ApiConfig;
use Upwork\API\Interfaces\Client as ApiClient;
use Upwork\API\Utils as ApiUtils;
use Upwork\API\ApiException as ApiException;

/**
 * Abstract OAuth Client
 */
abstract class AbstractOAuth
{

    const URL_AUTH      = '/services/api/auth';
    const URL_ATOKEN    = '/auth/v1/oauth/token/access';
    const URL_RTOKEN    = '/auth/v1/oauth/token/request';

    /**
     * @var Consumer key
     */
    static protected $_apiKey = null;
    /**
     * @var Consumer secret
     */
    static protected $_secret = null;
    /**
     * @var oauth_token shared request token (temporary)
     */
    static protected $_requestToken = null;
    /**
     * @var oauth_token_secret (temporary)
     */
    static protected $_requestSecret = null;
    /**
     * @var Final access token
     */
    static protected $_accessToken = null;
    /**
     * @var Final access token secret
     */
    static protected $_accessSecret = null;
    /**
     * @var OAuth verifier
     */
    static protected $_verifier = null;
    /**
     * @var Entry point name
     */
    static protected $_epoint = 'api';
    /**
     * @var Application mode
     */
    static protected $_mode = 'web';
    /**
     * @var SSL verification flag
     */
    static protected $_verifySsl = true;
    /**
     * @var Signature method
     */
    static protected $_sigMethod = 'HMAC-SHA1';

    /**
     * Constructor
     *
     * @param   string $key Application key
     * @param	string $secret Secret key
     * @access  public
     * @throws  ApiException Wrong key or secret
     */
    public function __construct($key, $secret)
    {
        ApiDebug::p('starting ' . __CLASS__ . ' authentication');

        if (!$secret) {
            throw new ApiException('You must define "secret key".');
        } else {
            self::$_secret = (string) $secret;
        }

        if (!$key) {
            throw new ApiException('You must define "application key".');
        } else {
            self::$_apiKey = (string) $key;
        }
    }

    /**
     * Set option
     *
     * @param   string $option Option name
     * @param   mixed $value Option value
     * @access  public
     * @return  boolean
     */
    public static function option($option, $value)
    {
        $name = '_' . $option;

        $r = new \ReflectionClass('\\' . __CLASS__);
        try {
            $r->getProperty($name);
            self::$$name = $value;
            return true;
        } catch (\ReflectionException $e) {
            return false;
        }
    }

    /**
     * Auth process
     *
     * @access  public
     * @return  string
     */
    public function auth()
    {
        ApiDebug::p('running auth process in ' . __CLASS__);

        if (self::$_accessToken === null && self::$_verifier === null) {
            if (self::$_requestToken === null && self::$_requestSecret === null) {
                // web-based application should setup and save request token itself
                // to be able use it after callback
                $this->setupRequestToken();
            }

            $authUrl = ApiUtils::getFullUrl(self::URL_AUTH) .
            '?oauth_token=' . self::$_requestToken;

            if (self::$_mode === 'web') {
                // authorize web application via browser
                header('Location: ' . $authUrl);
            } elseif (self::$_mode === 'nonweb') {
                // authorize nonweb application
                ApiDebug::p('found [nonweb] mode, need to authorize application manually');

                $prompt = 'Visit ' . $authUrl . "\n " .
                    'and provide oauth_verifier for further authorization' . "\n" .
                    '$ ';
                if (PHP_OS == 'WINNT') {
                    echo $prompt;
                    $verifier = stream_get_line(STDIN, 1024, PHP_EOL);
                } else {
                    $verifier = readline($prompt);
                }

                // get access token
                $this->_setupAccessToken($verifier);
            }
        } elseif (self::$_accessToken === null && self::$_verifier !== null) {
            // get access token, web-based callback
            $this->_setupAccessToken(self::$_verifier);
        } else {
            // access_token isset
        }

        return array(
            'access_token'  => self::$_accessToken,
            'access_secret' => self::$_accessSecret
        );
    }

    /**
     * Get access token
     *
     * @param	string $verifier OAuth verifier, got after authorization
     * @access	private
     * @return	array
     */
    abstract protected function _setupAccessToken($verifier);

    /**
     * Get OAuth instance
     *
     * @param   integer $authType Auth type
     * @access  public
     * @return  object
     */
    abstract protected function _getOAuthInstance($authType);
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Custom Payments
 *
 * @final
 * @package     UpworkAPI
 * @since       05/02/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Custom Payments
 *
 * @link http://developers.upwork.com/Custom-Payment-API
 */
final class Payments extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Submit a Custom Payment
     *
     * @param   integer $teamReference Team reference
     * @param   array $params Parameters
     * @return  object
     */
    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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Get oTask/Activity records by contract/engagement
 *
 * @final
 * @package     UpworkAPI
 * @since       08/04/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Activities;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Get an Activity records by contract/engagement
 *
 * @link http://developers.upwork.com/oTasks-API
 */
final class Engagement extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * List activities for specific engagement
     *
     * @param   integer $engagementRef Engagement reference
     * @return  object
     */
    public function getSpecific($engagementRef)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/tasks/v2/tasks/contracts/' . $engagementRef);
        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 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 to specific engagement the list of activities
     *
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       04/22/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\AuthTypes;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Config as ApiConfig;
use Upwork\API\Interfaces\Client as ApiClient;
use Upwork\API\Utils as ApiUtils;
use Upwork\API\ApiException as ApiException;
use Upwork\API\AuthTypes\AbstractOAuth as AbstractOAuth;

// Iclude own library
require_once __DIR__ . '/../../../../vendor-src/oauth-php/library/OAuthStore.php';
require_once __DIR__ . '/../../../../vendor-src/oauth-php/library/OAuthRequester.php';

/**
 * OAuth 1.0a Client based on OAuth PHP Library as an example
 * see https://code.google.com/p/oauth-php/
 */
final class OAuthPHPLib extends AbstractOAuth implements ApiClient
{
    /**
     * Get instance
     *
     * @return  object
     * @access  public
     */
    public function getInstance()
    {
        return $this->_getOAuthInstance();
    }

    /**
     * Do request
     *
     * @param   string $type Type of request
     * @param   string $url URL
     * @param   array $params (Optional) Parameters
     * @access  public
     * @return  mixed
     */
    public function request($type, $url, $params = array())
    {
        ApiDebug::p('running request from ' . __CLASS__);

        $this->_getOAuthInstance();

        $request = new \OAuthRequester(ApiUtils::getFullUrl($url, self::$_epoint), $type, $params);
        $data = $request->doRequest(0, self::_getCurlOptions());

        ApiDebug::p('got response from server', $data);

        return $data['body'];
    }

    /**
     * Get and setup request token
     *
     * @access  public
     * @return  array
     */
    public function setupRequestToken()
    {
        ApiDebug::p('query request token from server');

        $this->_getOAuthInstance();
        $requestTokenInfo = \OAuthRequester::requestRequestToken(
            self::$_apiKey,
            0,
            array(),
            'POST',
            array(),
            self::_getCurlOptions()
        );

        // add token_secret to response
        $requestTokenInfo['token_secret'] = $_SESSION['oauth_' . self::$_apiKey]['token_secret'];

        ApiDebug::p('got request token info', $requestTokenInfo);

        self::$_requestToken  = $requestTokenInfo['token'];
        self::$_requestSecret = $requestTokenInfo['token_secret'];

        return array('oauth_token' => $requestTokenInfo['token'], 'oauth_token_secret' => $requestTokenInfo['token_secret']);
    }

    /**
     * Get access token
     *
     * @param	string $verifier OAuth verifier, got after authorization
     * @access	protected
     * @return	array
     */
    protected function _setupAccessToken($verifier)
    {
        ApiDebug::p('requesting access token');

        $accessTokenInfo = array();

        $this->_getOAuthInstance();
        \OAuthRequester::requestAccessToken(
            self::$_apiKey,
            self::$_requestToken,
            0,
            'POST',
            array('oauth_verifier' => $verifier),
            self::_getCurlOptions()
        );

        $accessTokenInfo['oauth_token']         = $_SESSION['oauth_' . self::$_apiKey]['token'];
        $accessTokenInfo['oauth_token_secret']  = $_SESSION['oauth_' . self::$_apiKey]['token_secret'];

        ApiDebug::p('got access token info', $accessTokenInfo);

        self::$_accessToken     = $accessTokenInfo['oauth_token'];
        self::$_accessSecret    = $accessTokenInfo['oauth_token_secret'];

        return $accessTokenInfo;
    }

    /**
     * Get OAuth instance
     *
     * @param   integer $authType (Optional) Auth type
     * @access  protected
     * @return  object
     */
    protected function _getOAuthInstance($authType = null)
    {
        ApiDebug::p('get OAuth instance');

        $options = array(
            'consumer_key' => self::$_apiKey,
            'consumer_secret' => self::$_secret,
            'server_uri' => UPWORK_BASE_URL,
            'request_token_uri' => ApiUtils::getFullUrl(self::URL_RTOKEN, 'api'),
            'authorize_uri' => self::URL_AUTH,
            'access_token_uri' => ApiUtils::getFullUrl(self::URL_ATOKEN, 'api')
        );

        $oauth = \OAuthStore::instance('Session', $options);

        return $oauth;
    }

    /**
     * Get curl options
     *
     * @static
     * @return  array
     * @access  private
     */
    private static function _getCurlOptions()
    {
        $options = array();
        $options[CURLOPT_SSL_VERIFYPEER] = self::$_verifySsl;

        return $options;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * My Info
 *
 * @final
 * @package     UpworkAPI
 * @since       04/21/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * My Info
 *
 * @link http://developers.upwork.com/My%20Info
 */
final class Auth extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * My Info
     *
     * @return object
     */
    public function getUserInfo()
    {
        ApiDebug::p(__FUNCTION__);

        $info = $this->_client->get('/auth/v1/info');
        ApiDebug::p('found auth info', $info);

        return $info;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Financial Reporting
 *
 * @final
 * @package     UpworkAPI
 * @since       05/02/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Reports\Finance;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Financial Reporting
 *
 * @link http://developers.upwork.com/Financial-Reports-GDS-API
 */
final class Earnings extends ApiClient
{
    const ENTRY_POINT = UPWORK_GDS_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Generate Earning Reports for a Specific Freelancer
     *
     * @param   integer $freelancerReference Freelancer reference
     * @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;
    }

    /**
     * Generate Earning Reports for a Specific Freelancer's Team
     *
     * @param   integer $freelancerTeamReference Freelancer team 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;
    }

    /**
     * Generate Earning Reports for a Specific Freelancer's Company
     *
     * @param   integer $freelancerCompanyReference Freelancer company reference
     * @param   array $params Parameters
     * @return  object
     */
    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 Buyer's Team
     *
     * @param   integer $buyerTeamReference Buyer team reference
     * @param   array $params Parameters
     * @return  object
     */
    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 Company
     *
     * @param   integer $buyerCompanyReference Buyer company reference
     * @param   array $params Parameters
     * @return  object
     */
    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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Engagements
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Engagements API
 *
 * @link http://developers.upwork.com/Engagements-API
 */
final class Engagements extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get list of engagements
     *
     * @param   array $params Parameters
     * @return  object
     */
    public function getList($params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $engagements;
    }

    /**
     * Get specific engagement
     *
     * @param   integer $reference Engagement's reference
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       04/21/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API;

use Upwork\API\Debug as ApiDebug;

/**
 * Utils
 */
final class Utils
{
    /**
     * Get full url, based on global constant
     *
     * @param	string $url Relative URL
     * @param	string $ep (Optional) Entry point
     * @static
     * @access	public
     * @return	string
     */
    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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Freelancer's Offers
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr\Freelancers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Freelancer Job Offers API
 *
 * @link http://developers.upwork.com/w/page/70448095/Contractor%20Offers
 */
final class Offers extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get list of offers
     *
     * @param   array $params Parameters
     * @return  object
     */
    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 specific offer
     *
     * @param   integer $reference Offer reference
     * @return  object
     */
    public function getSpecific($reference)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/offers/v1/contractors/offers/' . $reference);
        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 actions($reference, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Financial Reporting
 *
 * @final
 * @package     UpworkAPI
 * @since       05/02/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Reports\Finance;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Financial Reporting
 *
 * @link http://developers.upwork.com/Financial-Reports-GDS-API
 */
final class Accounts extends ApiClient
{
    const ENTRY_POINT = UPWORK_GDS_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Generate Financial Reports for an owned Account
     *
     * @param   integer $freelancerReference Freelancer reference
     * @param   array $params Parameters
     * @return  object
     */
    public function getOwned($freelancerReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $report;
    }

    /**
     * Generate Financial Reports for a Specific Account
     *
     * @param   integer $entityReference Entity reference
     * @param   array $params Parameters
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * User Roles
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * User Roles
 *
 * @link http://developers.upwork.com/User-Roles
 */
final class Roles extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get user roles
     *
     * @return object
     */
    public function getAll()
    {
        ApiDebug::p(__FUNCTION__);

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

        return $roles;
    }

    /**
     * Get by specific user
     *
     * @param   integer $reference User reference
     * @return  object
     */
    public function getBySpecificUser($reference)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $roles;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Invite to Interview
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Invite to Interview
 *
 * @link http://developers.upwork.com/w/page/23873221/Jobs%20HR%20API
 */
final class Interviews extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Invite to Interview
     *
     * @param   string $jobKey Job key
     * @param   array $params Parameters
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Time Reporting
 *
 * @final
 * @package     UpworkAPI
 * @since       05/02/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Reports;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Financial Reporting
 *
 * @link http://developers.upwork.com/Time-Reports-API
 */
final class Time extends ApiClient
{
    const ENTRY_POINT = UPWORK_GDS_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Generate Time Reports for a Specific Team/Comapny/Agency
     *
     * @param   string $company Company ID
     * @param   string $team (Optional) Team ID
     * @param   string $agency (Optional) Agency ID
     * @param   array $params (Optional) Parameters
     * @param   boolean $hideFinDetails (Optional) Hides all financial details
     * @return  object
     */
    private function _getByType($company, $team = null, $agency = null, $params = array(), $hideFinDetails = false)
    {
        ApiDebug::p(__FUNCTION__);

        $_url = '';
        if ($team) {
            $_url = '/teams/' . $team;
            if ($hideFinDetails) {
                $_url .= '/hours';
            }
        } elseif ($agency) {
            $_url = '/agencies/' . $agency;
        }

        $report = $this->_client->get('/timereports/v1/companies/' . $company . $_url, $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

    /**
     * Generate Time Reports for a Specific Team (with financial info)
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByTeamFull($company, $team, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

    /**
     * Generate Time Reports for a Specific Team (hide financial info)
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByTeamLimited($company, $team, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

    /**
     * Generating Agency Specific Reports
     *
     * @param   string $company Company ID
     * @param   string $agency Agency ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByAgency($company, $agency, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

    /**
     * Generating Company Wide Reports
     *
     * @param   string $company Company ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByCompany($company, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

    /**
     * Generating Freelancer Specific Reports (hide financial info)
     *
     * @param   string $freelancerId Freelancer ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByFreelancerLimited($freelancerId, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/timereports/v1/providers/' . $freelancerId . '/hours', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

    /**
     * Generating Freelancer Specific Reports (with financial info)
     *
     * @param   string $freelancerId Freelancer ID
     * @param   array $params Parameters
     * @return  object
     */
    public function getByFreelancerFull($freelancerId, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/timereports/v1/providers/' . $freelancerId, $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Teams info
 *
 * @final
 * @package     UpworkAPI
 * @since       05/16/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Organization;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Teams info
 *
 * @link http://developers.upwork.com/Organization-APIs
 */
final class Teams extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get Teams info
     *
     * @return object
     */
    public function getList()
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Get Users in Team
     *
     * @param   integer $teamReference Team reference
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Workdays API
 *
 * @final
 * @package     UpworkAPI
 * @since       07/14/2015
 * @copyright   Copyright 2015(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Workdays API
 *
 * @link http://developers.upwork.com/#companies-and-teams_get-workdays-by-company
 */
final class Workdays extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get Workdays
     *
     * @param   string $company Company ID
     * @param   string $fromDate Start date
     * @param   string $tillDate Till date
     * @param   array $params (Optional) Parameters
     * @return  object
     */
    public function getByCompany($company, $fromDate, $tillDate, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/team/v3/workdays/companies/' . $company . '/' . $fromDate . ',' . $tillDate, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

    /**
     * Get Workdiary by Contract
     *
     * @param   string $contract Contract ID
     * @param   string $fromDate Start date
     * @param   string $tillDate Till date
     * @param   array $params (Optional) Parameters
     * @return  object
     */
    public function getByContract($contract, $fromDate, $tillDate, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/team/v3/workdays/contracts/' . $contract . '/' . $fromDate . ',' . $tillDate, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Jobs
 *
 * @final
 * @package     UpworkAPI
 * @since       05/09/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Jobs API
 *
 * @link http://developers.upwork.com/Jobs-HR-API
 */
final class Jobs extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get list of jobs
     *
     * @param   array $params Parameters
     * @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;
    }

    /**
     * Get specific job by key
     *
     * @param   string $key Job key
     * @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;
    }

    /**
     * Post a new job
     *
     * @param   array $params Parameters
     * @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;
    }

    /**
     * Edit existend job
     *
     * @param   string $key Job key
     * @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;
    }

    /**
     * Delete 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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Get users info
 *
 * @final
 * @package     UpworkAPI
 * @since       05/16/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Organization;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Get user info
 *
 * @link http://developers.upwork.com/Organization-APIs
 */
final class Users extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get Auth User Info
     *
     * @return object
     */
    public function getMyInfo()
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Get Specific User Info
     *
     * @param integer $userReference User Reference
     * @return object
     */
    public function getSpecific($userReference)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Get oTask/Activity records within a team
 *
 * @final
 * @package     UpworkAPI
 * @since       05/21/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Activities;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Get an oTask/Activity records within a team
 *
 * @link http://developers.upwork.com/oTasks-API
 */
final class Team extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get by type
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   string $code (Optional) Code(s)
     * @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;
    }

    /**
     * List all oTask/Activity records within a Team
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @return  object
     */
    public function getList($company, $team)
    {
        ApiDebug::p(__FUNCTION__);

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

    /**
     * List all oTask/Activity records within a Team by specified code(s)
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   string $code Specific code(s)
     * @return  object
     */
    public function getSpecificList($company, $team, $code)
    {
        ApiDebug::p(__FUNCTION__);

        return $this->_getByType($company, $team, $code);
    }

    /**
     * Create an oTask/Activity record within a Team
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   array $params Parameters
     * @return  object
     */
    public function addActivity($company, $team, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Update specific oTask/Activity record within a Team
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   string $code Specific code
     * @param   array $params Parameters
     * @return  object
     */
    public function updateActivity($company, $team, $code, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Archive specific oTask/Activity record within a Team
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   string $code Specific code(s)
     * @return  object
     */
    public function archiveActivities($company, $team, $code)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Unarchive specific oTask/Activity record within a Team
     *
     * @param   string $company Company ID
     * @param   string $team Team ID
     * @param   string $code Specific code(s)
     * @return  object
     */
    public function unarchiveActivities($company, $team, $code)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       06/13/2016
 * @copyright   Copyright 2016(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Messages
 *
 * @link https://developers.upwork.com/#messages-new
 */
final class Messages extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Retrieve rooms information
     *
     * @param   array $params List of parameters
     * @access  public
     * @return  object
     */
    public function getRooms($company, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/messages/v3/' . $company . '/rooms', $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 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 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 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 application ID
     *
     * @param   string $company Company ID
     * @param	integer $applicationId Application 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;
    }

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

    /**
     * Create a new room
     *
     * @param   string $company Company 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;
    }

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

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


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Snapshot info
 *
 * @final
 * @package     UpworkAPI
 * @since       05/19/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Snapshot info
 *
 * @link http://developers.upwork.com/Snapshot
 */
final class Snapshot extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get snapshot info by specific contract
     *
     * @param   string $contractId Contract ID
     * @param   string $ts Timestamp
     * @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;
    }

    /**
     * Update snapshot by specific contract
     *
     * @param   string $contractId Contract ID
     * @param   string $ts Timestamp
     * @param   array $params Parameters
     * @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;
    }

    /**
     * Delete snapshot by specific contract
     *
     * @param   string $contractId Contract ID
     * @param   string $ts Timestamp
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       04/22/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\AuthTypes;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Config as ApiConfig;
use Upwork\API\Interfaces\Client as ApiClient;
use Upwork\API\Utils as ApiUtils;
use Upwork\API\ApiException as ApiException;
use Upwork\API\AuthTypes\AbstractOAuth as AbstractOAuth;

/**
 * OAuth 1.0a Client
 */
final class OAuth1 extends AbstractOAuth implements ApiClient
{
    /**
     * Do request
     *
     * @param   string $type Type of request
     * @param   string $url URL
     * @param   array $params (Optional) Parameters
     * @static
     * @access  public
     * @return  mixed
     */
    public function request($type, $url, $params = array())
    {
        ApiDebug::p('running request from ' . __CLASS__);

        $authType = ($type == 'GET') ? OAUTH_AUTH_TYPE_URI : OAUTH_AUTH_TYPE_FORM;

        $oauth = $this->_getOAuthInstance($authType);

        $oauth->setToken(self::$_accessToken, self::$_accessSecret);
        try {
            $oauth->fetch(ApiUtils::getFullUrl($url, self::$_epoint), $params, $type);
        } catch (\OAuthException $e) {
            //
        }

        $data = $oauth->getLastResponse();

        ApiDebug::p('got response from server', $data);

        return $data;
    }

    /**
     * Get and setup request token
     *
     * @access  public
     * @return  array
     */
    public function setupRequestToken()
    {
        ApiDebug::p('query request token from server');

        $oauth = $this->_getOAuthInstance(OAUTH_AUTH_TYPE_FORM);
        $requestTokenInfo = $oauth->getRequestToken(
            ApiUtils::getFullUrl(self::URL_RTOKEN, 'api')
        );
        ApiDebug::p('got request token info', $requestTokenInfo);

        self::$_requestToken  = $requestTokenInfo['oauth_token'];
        self::$_requestSecret = $requestTokenInfo['oauth_token_secret'];

        return $requestTokenInfo;
    }

    /**
     * Get access token
     *
     * @param	string $verifier OAuth verifier, got after authorization
     * @access	protected
     * @return	array
     */
    protected function _setupAccessToken($verifier)
    {
        ApiDebug::p('requesting access token');

        $oauth = $this->_getOAuthInstance(OAUTH_AUTH_TYPE_FORM);
        $oauth->setToken(self::$_requestToken, self::$_requestSecret);
        $accessTokenInfo = $oauth->getAccessToken(
            ApiUtils::getFullUrl(self::URL_ATOKEN, 'api'),
            null,
            $verifier
        );

        ApiDebug::p('got access token info', $accessTokenInfo);

        self::$_accessToken     = $accessTokenInfo['oauth_token'];
        self::$_accessSecret    = $accessTokenInfo['oauth_token_secret'];

        return $accessTokenInfo;
    }

    /**
     * Get OAuth instance
     *
     * @param   integer $authType Auth type
     * @access  protected
     * @return  object
     */
    protected function _getOAuthInstance($authType)
    {
        ApiDebug::p('get OAuth instance');

        $oauth = new \OAuth(
            self::$_apiKey,
            self::$_secret,
            self::$_sigMethod,
            $authType
        );

        if (ApiConfig::get('debug')) {
            $oauth->enableDebug();
        }

        if (!self::$_verifySsl) {
            $oauth->disableSSLChecks();
        }

        return $oauth;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 * Work with Milestones
 *
 * @final
 * @package     UpworkAPI
 * @since       11/17/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API\Routers\Hr;

use Upwork\API\Debug as ApiDebug;
use Upwork\API\Client as ApiClient;

/**
 * Milestones
 *
 * @link https://developers.upwork.com/?lang=php#contracts-and-offers
 */
final class Milestones extends ApiClient
{
    const ENTRY_POINT = UPWORK_API_EP_NAME;

    /**
     * @var Client instance
     */
    private $_client;

    /**
     * Constructor
     *
     * @param   ApiClient $client Client object
     */
    public function __construct(ApiClient $client)
    {
        ApiDebug::p('init ' . __CLASS__ . ' router');
        $this->_client = $client;
        parent::$_epoint = self::ENTRY_POINT;
    }

    /**
     * Get active Milestone for specific Contract
     *
     * @param   integer $contractId Contract reference
     * @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 all Submissions for specific Milestone
     *
     * @param   integer $milestoneId Milestone ID
     * @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;
    }

    /**
     * Create a new Milestone
     *
     * @param   array $params Parameters
     * @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;
    }

    /**
     * Edit an existing Milestone
     *
     * @param   integer $milestoneId Milestone ID
     * @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;
    }

    /**
     * Activate an existing Milestone
     *
     * @param   integer $milestoneId Milestone ID
     * @param   array $params Parameters
     * @return  object
     */
    public function activate($milestoneId, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Approve an existing Milestone
     *
     * @param   integer $milestoneId Milestone ID
     * @param   array $params Parameters
     * @return  object
     */
    public function approve($milestoneId, $params)
    {
        ApiDebug::p(__FUNCTION__);

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

        return $response;
    }

    /**
     * Delete an existing Milestone
     *
     * @param   integer $milestoneId Milestone ID
     * @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;
    }
}


<?php
/**
 * Upwork auth library for using with public API by OAuth
 *
 * @final
 * @package     UpworkAPI
 * @since       04/21/2014
 * @copyright   Copyright 2014(c) Upwork.com
 * @author      Maksym Novozhylov <mnovozhilov@upwork.com>
 * @license     Upwork's API Terms of Use {@link https://developers.upwork.com/api-tos.html}
 */

namespace Upwork\API;

use Upwork\API\Config as ApiConfig;
use Upwork\API\Debug as ApiDebug;
use Upwork\API\Utils as ApiUtils;

/**
 * Client
 */
class Client
{
    // we will deal only with json inside library
    // and return already decoded data
    const DATA_FORMAT = 'json';

    /**
     * @var Entry point name
     */
    static protected $_epoint = UPWORK_API_EP_NAME;

    /**
     * @var Server instance (AuthTypes)
     */
    protected $_server;

    /**
     * Constructor
     *
     * @param   ApiConfig $config Config object
     * @access  public
     */
    public function __construct(ApiConfig $config)
    {
        ApiDebug::p('preparing Client');

        $key	    = $config::get('consumerKey');
        $secret     = $config::get('consumerSecret');
        $aToken     = $config::get('accessToken');
        $aSecret    = $config::get('accessSecret');
        $verifySsl  = $config::get('verifySsl');
        $auth       = 'Upwork\API\AuthTypes\\' . $config::get('authType');

        $this->_server = new $auth($key, $secret);
        !$aToken  || $this->_server->option('accessToken', $aToken);
        !$aSecret || $this->_server->option('accessSecret', $aSecret);
        $this->_server->option('verifySsl', $verifySsl);
    }

    /**
     * Get server instance
     *
     * @return  object
     * @access  public
     */
    public function getServer()
    {
        return $this->_server;
    }

    /**
     * Get request token for web-base apps
     *
     * @access  public
     * @return  array
     */
    public function getRequestToken()
    {
        ApiDebug::p('getRequestToken');

        return $this->_server->setupRequestToken();
    }

    /**
     * Auth application
     *
     * @access  public
     * @return  mixed
     */
    public function auth()
    {
        ApiDebug::p('authing Client');

        $this->_server->option('mode', ApiConfig::get('mode'));
        $this->_server->option('sigMethod', ApiConfig::get('sigMethod'));

        // setup request tokens for web-based app
        // they must be already obrained on the first step
        if (ApiConfig::get('mode') === 'web') {
            $rToken     = ApiConfig::get('requestToken');
            $rSecret    = ApiConfig::get('requestSecret');
            $oVerifier  = ApiConfig::get('verifier');

            !$rToken 	|| $this->_server->option('requestToken', $rToken);
            !$rSecret	|| $this->_server->option('requestSecret', $rSecret);
            !$oVerifier || $this->_server->option('verifier', $oVerifier);
        }

        return $this->_server->auth();
    }

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

    /**
     * Do GET request
     *
     * @param   string $url API URL
     * @param   array $params (Optional) Additional parameters
     * @access  public
     * @return  mixed
     */
    public function get($url, $params = array())
    {
        ApiDebug::p('starting GET request');
        return $this->_request('GET', $url, $params);
    }

    /**
     * Do POST request
     *
     * @param   string $url API URL
     * @param   array $params (Optional) Additional parameters
     * @access  public
     * @return  mixed
     */
    public function post($url, $params = array())
    {
        ApiDebug::p('starting POST request');
        return $this->_request('POST', $url, $params);
    }

    /**
     * Do PUT request
     *
     * @param   string $url API URL
     * @param   array $params (Optional) Additional parameters
     * @access  public
     * @return  mixed
     */
    public function put($url, $params = array())
    {
        ApiDebug::p('starting PUT request');
        return $this->_request('PUT', $url, $params);
    }

    /**
     * Do DELETE request
     *
     * @param   string $url API URL
     * @param   array $params (Optional) Additional parameters
     * @access  public
     * @return  mixed
     */
    public function delete($url, $params = array())
    {
        ApiDebug::p('starting DELETE request');
        return $this->_request('DELETE', $url, $params);
    }
}


<?php
/*
 * This file is part of the Laravel Facebook Account-Kit package.
 *
 * (c) Ibraheem Adeniyi <ibonly01@gmail.com>
 * (c) Surajudeen Akande <surajudeen.akande@andela.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Ibonly\FacebookAccountKit;

use Illuminate\Support\ServiceProvider;

class FacebookAccountKitServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Publishes all the config file this package needs to function
     */
    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');
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->app->singleton('AccountKit', function() {

            return new FacebookAccountKit;
        });
    }

    /**
     * Get the services provided by the provider
     *
     * @return array
     */
    public function provides()
    {
        return ['AccountKit'];
    }
}