Search
Search
Search
Search
Information
Information
Light
Dark
Open actions menu
Basic upload method
Bypass upload method
Tips!
If you encounter an error (by firewall) while uploading using both methods,
try changing extension of the file before uploading it and rename it right after.
This uploader supports multiple file upload.
Submit
~
var
www
podiocopy.bitkit.dk
httpdocs
app
Http
Controllers
Transfer
File Content:
TestController.php
<?php /** * Created by PhpStorm. * User: jis * Date: 21/5/15 * Time: 6:08 PM */ namespace App\Http\Controllers\Transfer; //use Illuminate\Support\Facades\Config; use MongoDB; use App\Http\Controllers\Controller; use App\Http\Modules\ShareFileRepository; use App\Modules\Application\AppMoveRepo; use App\Modules\Application\AppToAppMoveRepo; use App\Modules\Application\CalculationRepo; use App\Modules\Application\PodioAppModel; use App\Modules\Auth\AuthRepository; use App\Modules\Auth\PodioDBSession; use App\Modules\Auth\User; use App\Modules\CheckRights\CheckRightsRepo; use App\Modules\GenModels\ApprovedProfiles; use App\Modules\GenModels\IgnoredProfiles; use App\Modules\GenModels\PrimaryKeyItems; use App\Modules\GenModels\TransferQueue; use App\Modules\Item\AppToAppItemRepo; use App\Modules\Item\ItemModel; use App\Modules\Item\ItemRepo; use App\Modules\Item\TaskTempModel; use App\Modules\Logs\LogAll; use App\Modules\WorkSpace\WorkSpaceModel; use App\Modules\WorkSpace\WorkSpaceMoveRepo; use App\Modules\WorkSpace\WorkSpaceStreamModel; use DateTime; use DateTimeZone; use Exception; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Crypt; use MongoDB\BSON\ObjectId; use MongoId; use Podio; use PodioApp; use PodioAppField; use PodioComment; use PodioContact; use PodioEmbed; use PodioError; use PodioFile; use PodioFlow; use PodioHook; use PodioItem; use PodioItemDiff; use PodioItemRevision; use PodioNotFoundError; use Log; use Mail; use App\Modules\Configurations\Config; use Illuminate\Contracts\Logging\Log as LoggingLog; use PodioOAuth; use PodioOrganization; use PodioSearchResult; use PodioSpace; use PodioSpaceMember; use PodioStatus; use PodioStreamObject; use PodioTag; use PodioTask; use PodioUser; use PodioUserStatus; use PodioView; use PodioWidget; use Traversable; use Input; use phpDocumentor\Reflection\Types\Null_; use App\Modules\GenModels\PhasesPay; use Firebase\JWT\JWT; use App\Http\Requests\Request; class TestController extends Controller { public function __construct() { $this->authRepo = new AuthRepository(); $this->transferQModel = new TransferQueue(); $this->user = new User(); $this->itemModel = new ItemModel(); $this->podioAppsModel = new PodioAppModel(); $this->appRepo = new AppToAppMoveRepo(); $this->pkModel = new PrimaryKeyItems(); $this->queueModel = new TransferQueue(); $this->ignoredProfile = new IgnoredProfiles(); $this->approvedProfile = new ApprovedProfiles(); $this->workspaceStreamModel = new WorkSpaceStreamModel(); $this->user = new User(); $this->workSpaceModel = new WorkSpaceModel(); try { ini_set('memory_limit', '-1'); ini_set('max_execution_time', '-1'); ini_set("auto_detect_line_endings", true); } catch (Exception $e) { Log::error($e); } } /** * */ // https://podiocopy.phases.dk/test/ public function getIndex() { try { $this->setupPodio(); $completed_steps[] = "All Items Moved To New App"; $this->podioAppsModel->update( array('app_id' => 21205354), array("status" => "completed", "next_step" => "app_completed_process_next_app", "completed_steps" => $completed_steps) ); dd('done'); $this->transferQModel->update(array('_id' => new ObjectId('5f86a763413f0a6935613e97')), array('status' => 'completed')); $items = $this->workspaceStreamModel->getStreams(array('space_id' => 7110303, 'queue_id' => '5f869ea9eeeb05274133f628')); dd(count($items->toArray())); foreach ($items as $item) { dd($item); } $userId = "5f7d6636e3eef671360bba82"; if ($this->authRepo->authenticateUser($userId)) { $items = $this->itemModel->find(array( 'queue_id' => "5f82c3cc67e23a3192405653", 'comment_status' => 'not_completed' )); echo "<pre>"; print_r($items); } else { echo "No auth"; } } catch (Exception $e) { dd($e); } } public function getRemoveUsers() { $workspace = Input::get('ws'); $email = Input::get('email'); try { $userId = "5ca1efdfb500884c1b7b23c6"; // $userId = "556c4e4a21b4d648635ce70d"; if ($this->authRepo->authenticateUser($userId)) { $limit = 100; $offset = 0; $attributes = array("limit" => $limit); do { $attributes['offset'] = $offset; $count = 0; $workSpaceMembers = Podio::get("/space/" . $workspace . "/member/", $attributes)->json_body(); if ($workSpaceMembers && is_array($workSpaceMembers) && count($workSpaceMembers) > 0) { $count = count($workSpaceMembers); foreach ($workSpaceMembers as $contact) { if ($contact['user']['mail'] != $email) { PodioSpaceMember::delete($workspace, $contact['profile']['user_id']); } } $offset += $limit; } } while ($count > 0); } } catch (Exception $e) { echo "<pre>"; print_r($e); Log::error($e); } } public function getSendMail() { // try { // $toEmail = "nvj@phases.dk"; // Mail::send('emails.completed', array("name" => "Nivin"), function ($message) use ($toEmail) { // $message->to($toEm / member / v2 / ail) // ->subject('Podio copy is complete'); // $message->from(Config::$CONTACT_US_EMAIL, Config::$CONTACT_US_EMAIL_NAME); // }); // } catch (Exception $e) { // Log::error($e); // } } public function getCheckViewCount() { try { $userId = "5c49b725b50088412e7b23c6"; echo "<pre>"; $totalCount = 0; if ($this->authRepo->authenticateUser($userId)) { $limit = 500; $offset = 0; do { $attributes = array( 'sort_desc' => true, 'limit' => $limit, 'offset' => $offset ); $itemCollection = PodioItem::filter_by_view(3591419, 40895944, $attributes, $options = array()); $count = count($itemCollection); $totalCount += $count; // print_r($count); // echo "<br>"; // exit; $offset += $limit; } while ($count >= $limit); print_r($totalCount); } } catch (Exception $e) { echo "<pre>"; print_r($e); Log::error($e); } } public function getCreateMissingItems() { try { $userId = "5c3cfa73b50088fb427b23c6"; $queueID = "5c3f8834b5008810287b23c6"; $queueModel = new TransferQueue(); $itemModel = new ItemModel(); $count = 0; $repo = new AppToAppItemRepo(); $appRepo = new AppToAppMoveRepo(); $missingCount = 0; $missingItems = array(); echo "<pre>"; if ($this->authRepo->authenticateUser($userId)) { $items = $this->itemModel->find(array('queue_id' => $queueID, 'status' => "not_completed", 'item_id' => array('$exists' => false))); if ($items) { foreach ($items as $item) { // $this->moveItem($item, 20230577); // $itemVal = PodioItem::get(764856728); // print_r($itemVal); // exit; $missingCount++; array_push($missingItems, $item['old_item_id']); } // $appRepo->doNextStepOfAppToAppMove($queueID); } } print_r($missingCount); try { Mail::send('emails.completed-missing', array("name" => "Nivin", "missingItems" => $missingItems), function ($message) { $message->to("nvj@phases.dk") ->subject('Podio copy is complete'); $message->from(Config::$CONTACT_US_EMAIL, Config::$CONTACT_US_EMAIL_NAME); }); } catch (Exception $e) { Log::error($e); } } catch (Exception $e) { echo "<pre>"; print_r($e); Log::error($e); exit; } } public function moveItem($item, $appID) { $queueModel = new TransferQueue(); $queue = $queueModel->findOne(array('_id' => new MongoId($item['queue_id']))); $repo = new AppToAppItemRepo(); log::info("Moving started of Item Id" . $item['old_item_id'] . ''); try { $itemData = PodioItem::get($item['old_item_id']); PodioDBSession::updateRateLimitGeneral($item['user']); $podioFields = array(); $checkForPk = false; $data = []; $data['fields'] = array(); $haveCalculation = false; $pkArray = []; $query = array("queue_id" => $item['queue_id']); $queryArray = []; $fieldRelations = array(); $dateArray = []; $dateFieldFound = false; $calculationFieldsArray = []; $updateContact = array(); foreach ($itemData->fields as $field) { foreach ($queue["customMapping"] as $ind1 => $customMapping) { if ($customMapping['destApp']['destAppID'] == $item['new_app_id']) { if (isset($customMapping['primaryKeys'])) { $pkArray = []; foreach ($customMapping['primaryKeys'] as $key => $val) { $pkArray[] = $key; } } foreach ($customMapping["mapping"] as $ind2 => $mapping) { if ($mapping["fieldType"] == "date") { if (!$dateFieldFound) { $dateFieldGet = PodioAppField::get($item['new_app_id'], $mapping["destinationFieldID"]); if (isset($dateFieldGet->config['mapping']) && $dateFieldGet->config['mapping'] . '' == "meeting_time") $dateFieldFound = true; } // if (!in_array($mapping["destinationFieldID"], $dateArray)) { // $dateArray[] = $mapping["destinationFieldID"]; // } } if ($mapping["sourceFieldId"] == $field->field_id . '') { if (sizeof($pkArray) > 0) { if (in_array($field->field_id . '', $pkArray)) { $checkForPk = true; $query[$field->field_id . ''] = $field->values; } } if ($mapping["fieldType"] != "calculation") { if ($field) { switch ($mapping["fieldType"]) { case "contact": foreach ($field->values as $values) { $userExist = null; $ignoredProfile = null; $approvedProfile = null; $approvedProfile = $this->approvedProfile->findOne(array('profile_id' => $values->profile_id)); $ignoredProfile = $this->ignoredProfile->findOne(array('profile_id' => $values->profile_id)); $destAppField = PodioAppField::get((int)$customMapping['destApp']['destAppID'], (int)$mapping["destinationFieldID"]); $contactFieldType = $destAppField->config['settings']['type']; $ignoreUser = false; if ($contactFieldType . '' != "space_users_and_contacts" && $contactFieldType . '' != "space_contacts") { try { $spaceMember = PodioSpaceMember::get((int)$customMapping['destApp']['destSpaceID'], $values->user_id); } catch (Exception $e) { } if (isset($spaceMember) && !$spaceMember->role . '') { $ignoreUser = true; } } if (!$ignoreUser) { if (!$approvedProfile && !$ignoredProfile) { $userLink = $values->user_id; try { $userExist = PodioContact::get_for_user($userLink); } catch (Exception $e) { if ($contactFieldType . '' == "space_contacts") { $updateContact[$mapping["destinationFieldID"]][] = $values->profile_id; } } if ($userExist) { $userData = array("profile_id" => $values->profile_id, "user_id" => $values->user_id); $this->approvedProfile->create($userData); } else { $userData = array("profile_id" => $values->profile_id, "user_id" => $values->user_id); $this->ignoredProfile->create($userData); $ignoredProfile = true; } } if ($approvedProfile) $userExist = true; if ($userExist && !$ignoredProfile) { $podioFields[$mapping["destinationFieldID"]][] = $values->profile_id; } else { } } } break; case "email": $sourceIsText = false; $textValue = ''; if (is_array($field->values) or ($field->values instanceof Traversable)) { foreach ($field->values as $values) { if (isset($values['type'])) $podioFields[$mapping["destinationFieldID"]][] = array("type" => $values['type'], "value" => $values['value']); else { $sourceIsText = true; $textValue = $values['value']; } } } else { $sourceIsText = true; $textValue = $field->values; } if ($sourceIsText) { $string = str_replace(' ', '', $textValue); $string = str_replace('</p>', ',', $string); $string = strip_tags($string); $commaSeperatedValue = preg_split('/(,|;)/', $string); foreach ($commaSeperatedValue as $singleValue) { $singleValue = str_replace(' ', '', $singleValue); if (strlen(trim($singleValue)) != 0) $podioFields[$mapping["destinationFieldID"]][] = array("type" => 'work', "value" => $singleValue); } } break; case "phone": $sourceIsText = false; $textValue = ''; if (is_array($field->values) or ($field->values instanceof Traversable)) { foreach ($field->values as $values) { if (isset($values['type'])) $podioFields[$mapping["destinationFieldID"]][] = array("type" => $values['type'], "value" => $values['value']); else { $sourceIsText = true; $textValue = $values['value']; } } } else { $sourceIsText = true; $textValue = $field->values; } if ($sourceIsText) { $string = str_replace(' ', '', $textValue); $string = str_replace('</p>', ',', $string); $string = strip_tags($string); $commaSeperatedValue = preg_split('/(,|;)/', $string); foreach ($commaSeperatedValue as $singleValue) { $singleValue = str_replace(' ', '', $singleValue); if (strlen(trim($singleValue)) != 0) $podioFields[$mapping["destinationFieldID"]][] = array("type" => 'work', "value" => $singleValue); } } break; case "date": $itemDateData = PodioItem::get_basic($item['old_item_id']); $field_id = 'date'; $dateObject = true; if (isset($itemDateData->fields[$field_id]->values)) { if (array_key_exists("start", $itemDateData->fields[$field_id]->values)) { $dateValue = true; } else { $dateObject = false; } } else { $dateValue = $itemDateData->fields[$field_id]['start_time']; } if ($dateObject) { $startDate = null; $startTime = null; $endDate = null; $endTime = null; $start = null; $end = null; if (isset($field->values)) { if (is_array($field->values)) { $start = $field->values['start']; if ($field->values['end']) $end = $field->values['end']; } else { $start = $field->values->start; if ($field->values->end) $end = $field->values->end; } if ($start) { $startDate = $this->formatDate($start->format('Y-m-d'), $item['user']); if ($dateValue) $startTime = $this->formatTime($start->format('H:i:s'), $item['user']); if ($end) { $endDate = $this->formatDate($end->format('Y-m-d'), $item['user']); if ($dateValue) $endTime = $this->formatTime($end->format('H:i:s'), $item['user']); } } } else { if ($item['app_type'] . '' == "meeting") { $now = new DateTime(); $startDate = $this->formatDate($now->format('Y-m-d'), $item['user']); $startTime = $this->formatTime($now->format('H:i:s'), $item['user']); } } $podioFields[$mapping["destinationFieldID"]] = array("start_date" => $startDate, "start_time" => $startTime, "end_date" => $endDate, "end_time" => $endTime); } else { if ($item['app_type'] . '' == "meeting") { $now = new DateTime(); $startsDate = $this->formatDate($now->format('Y-m-d'), $item['user']); $startsTime = $this->formatTime($now->format('H:i:s'), $item['user']); $podioFields[$mapping["destinationFieldID"]] = array("start_date" => $startsDate, "start_time" => $startsTime); } else $podioFields[$mapping["destinationFieldID"]] = null; } break; case "embed": foreach ($field->values as $values) { $fileID = PodioEmbed::create($attributes = array("url" => $values->resolved_url)); $podioFields[$mapping["destinationFieldID"]][] = array("embed" => $fileID->embed_id); } break; case "image": foreach ($field->values as $values) { try { $fileID = PodioFile::copy($values->file_id); } catch (Exception $e) { log::error("No rights to add prev file"); } if (isset($fileID)) $podioFields[$mapping["destinationFieldID"]][] = array("value" => $fileID->file_id); } break; case "category": foreach ($field->values as $values) { if (isset($mapping['subCategory'])) { foreach ($mapping['subCategory'] as $subCategory) { if ($subCategory['sourceChildID'] == $values['id'] . '') { $podioFields[$mapping["destinationFieldID"]][] = (int)$subCategory['destinationFieldID']; } } } } break; default: if ($mapping["fieldType"] != "app") { if ($mapping["fieldType"] == "number") { if (is_numeric($field->values)) { $podioFields[$mapping["destinationFieldID"]] = $field->values; } } else $podioFields[$mapping["destinationFieldID"]] = $field->values; } break; } } if ($field->type == 'app') { foreach ($field->values as $value) { if (isset($value->item_id)) { if (!array_key_exists($field->external_id, $fieldRelations)) { $fieldRelations[$field->external_id] = array(); } $fieldRelations[$field->external_id][] = array( 'external_id' => $field->external_id, 'ref_item_id' => $value->item_id, 'ref_app_id' => $value->app->app_id, 'source_field_id' => $field->field_id ); } } } } else { $haveCalculation = true; $appField = PodioAppField::get($item['app_id'], $field->field_id); $config = $appField->config; $calculationFields = []; $calculationFields['script'] = $config['settings']['script']; $calculationFields['label'] = $config['label']; $calculationFields['delta'] = $config['delta']; $calculationFields['field_id'] = $field->field_id; $calculationFields['external_id'] = $field->external_id; array_push($data['fields'], $calculationFields); } } } } } } if ($haveCalculation) { $proceed = true; $data['have_calculation'] = true; $newApp = $this->podioAppsModel->findOne(array("app_id" => $item['app_id'], "queue_id" => $item['queue_id'])); if (isset($newApp['fields'])) { $proceed = false; if (count($newApp['fields']) < count($data['fields'])) $proceed = true; } if ($proceed) $this->podioAppsModel->update(array("app_id" => $item['app_id'], "queue_id" => $item['queue_id']), $data); } $fieldRelations = (count($fieldRelations) > 0) ? $fieldRelations : null; $this->itemModel->update(array("_id" => $item['_id']), array("field_relations" => $fieldRelations)); if ($pkArray) { if (sizeof($query) - sizeof($pkArray) != 1) $checkForPk = false; } if (sizeof($pkArray) > 0 && $checkForPk) { $pkModel = $this->pkModel->findOne($query); $updateItem = true; if ($pkModel) { $itemId = $pkModel['item_id']; } else $checkForPk = false; } $fileIDs = array(); if ($itemData->files) { foreach ($itemData->files as $file) { try { $fileCopy = PodioFile::copy($file->file_id); array_push($fileIDs, $fileCopy->file_id); } catch (Exception $e) { log::error("Can not copy Podio Files for item"); } } } // $podioFields = $this->removeEmptyKey($podioFields); if ($item['app_type'] . '' == "meeting") { if (!$dateFieldFound) { $attributes = []; $app = PodioApp::get($item['new_app_id'], $attributes); foreach ($app->fields as $appField) { if (isset($appField->config['mapping']) && $appField->config['mapping'] . '' == "meeting_time") { $dateFieldId = $appField->field_id; } } $now = new DateTime(); $startsDate = $this->formatDate($now->format('Y-m-d'), $item['user']); $startsTime = $this->formatTime($now->format('H:i:s'), $item['user']); $podioFields[$dateFieldId] = array("start_date" => $startsDate, "start_time" => $startsTime); } } if (count($fileIDs) > 0) { $podioAttributes = array('file_ids' => $fileIDs, 'fields' => $podioFields); } else { $podioAttributes = array('fields' => $podioFields); } $relationFieldIds = []; $podioApp = PodioApp::get($item['new_app_id'], array('type' => 'micro')); foreach ($podioApp->fields as $appField) if ($appField->type == "app") { if ($appField->status == "active") $relationFieldIds[] = $appField->id; } $relationFieldIds = (count($relationFieldIds) > 0) ? $relationFieldIds : null; $id = ''; // log::info($podioAttributes); if (!$checkForPk) { $response = PodioItem::create($item['new_app_id'], $podioAttributes, array('silent' => true)); $id = $response->item_id; if (count($updateContact) > 0) { $updateAttributes = array('fields' => $updateContact); PodioItem::update($response->item_id, $updateAttributes, array('silent' => true)); } $this->itemModel->update( array('_id' => $item['_id']), array( "item_id" => $response->item_id, "relationa_field_ids" => $relationFieldIds, "item_value_copy" => "completed", "next_step" => "copy_comment" ) ); } else { if (isset($itemId)) { $response = PodioItem::update($itemId, $podioAttributes, array('silent' => true)); if (count($updateContact) > 0) { $updateAttributes = array('fields' => $updateContact); PodioItem::update($itemId, $updateAttributes, array('silent' => true)); } $id = $itemId; $this->itemModel->update( array('_id' => $item['_id']), array( "item_id" => $itemId, "relationa_field_ids" => $relationFieldIds, "item_value_copy" => "completed", "next_step" => "copy_comment" ) ); } } PodioDBSession::updateRateLimit($item['user']); $tag = array(); if ($itemData->tags) { foreach ($itemData->tags as $tags) { $tag[] = $tags; } try { PodioTag::create('item', $id, $tag); } catch (Exception $e) { log::error("Tag cannot be added in item " . $id); } } if (PodioDBSession::getRateLimitRemains($item['user']) <= 100 || PodioDBSession::getRateLimitGenRemains($item['user']) <= 100) { Log::info("moveItem" . $item['queue_id'] . ":Rate limit remaining is less than 1000" . ", adding to trigger"); self::addTriggerForNextStepOfApp($item['queue_id'], 60); return; } $repo->doNextStepOfItmMove($item['queue_id'], $appID, $item); } catch (Exception $e) { echo "<pre>"; log::error($e); print_r($e); $this->itemModel->update( array('_id' => $item['_id']), array("item_value_copy" => "completed", "next_step" => "copy_comment") ); if (isset($podioAttributes)) log::info($podioAttributes); } } public function getAppsOnSpace() { echo "<pre>"; $userId = "5bc248d9b50088795bcd2e99"; if ($this->authRepo->authenticateUser($userId)) { try { $apps = PodioApp::get_for_space(6264482, $attributes = array()); foreach ($apps as $app) { print_r($app->config['name'] . " : " . $app->link . " : " . $app->app_id); echo "<br>"; } exit; } catch (Exception $e) { print_r($e); } } } public function getItemCount() { echo "<pre>"; $userId = "5bc248d9b50088795bcd2e99"; if ($this->authRepo->authenticateUser($userId)) { try { $limit = 200; $offset = 0; $totalCount = 0; $count = 0; do { $attributes = array( 'limit' => $limit, 'offset' => $offset ); try { $itemCollection = PodioItem::filter(24302297, $attributes, $options = array()); $count = count($itemCollection); echo "<pre>"; print_r($count); $totalCount += $count; } catch (Exception $e) { echo "<pre>"; print_r($e); } $offset += $limit; } while ($count >= $limit); echo "<br>"; print_r($totalCount); } catch (Exception $e) { print_r($e); exit; } } } public function getFieldPhases() { try { echo "<pre>"; $userId = "556c4e4a21b4d648635ce70d"; if ($this->authRepo->authenticateUser($userId)) { $limit = 200; $offset = 0; do { $attributes = array( 'filters' => array("created_on" => array("from" => "2017-12-11", "to" => "2017-12-15")) ); $itemCollection = PodioItem::filter(19248284, $attributes, $options = array()); $count = count($itemCollection); print_r($count); $offset += $limit; } while ($count >= $limit); } } catch (Exception $e) { print_r($e); } } public function getItemPhases() { echo "<pre>"; $userId = "556c4e4a21b4d648635ce70d"; if ($this->authRepo->authenticateUser($userId)) { $item = PodioItem::get(596985746); foreach ($item->fields as $fields) { if ($fields->external_id == "contact") { print_r($fields->values); } } } } public function getUser() { echo "<pre>"; $userId = "5b65f33eb500889835002519"; if ($this->authRepo->authenticateUser($userId)) { echo "Success"; } } public function getUpdateItems() { echo "<pre>"; // $userId = "582e033bb500880722ee1e30";5b65f33eb500889835002519 $userId = "1233"; if ($this->authRepo->authenticateUser($userId)) { $itemModel = new ItemModel(); $items = $itemModel->find(array('queue_id' => "5a3b0d51b50088765842a229")); if ($items) { foreach ($items as $item) { try { $updateItem = false; $profileId = array(); $newItem = PodioItem::get($item['old_item_id']); foreach ($newItem->fields as $fields) { if ($fields->field_id == 74995918) { $updateItem = true; foreach ($fields->values as $values) { $profileId[] = $values->profile_id; } } } if ($updateItem) { $podioFields = array(); $podioFields[163285640] = $profileId; $podioAttributes = array('fields' => $podioFields); $response = PodioItem::update($item['item_id'], $podioAttributes, array('silent' => true)); } } catch (Exception $e) { log::error($e); } } } } } public function getCheckComments() { echo "<pre>"; $userId = "59c26424b50088b16bce78c3"; if ($this->authRepo->authenticateUser($userId)) { $itemModel = new ItemModel(); $appModel = new PodioAppModel(); $items = $itemModel->find(array( 'queue_id' => "59c3066cb50088902f84b2ee", 'comment_status' => array('$ne' => 'new_completed') )); if ($items) { // check rate limit between 10 items $limitCheck = 0; $itemRepo = new ItemRepo(); foreach ($items as $item) { try { $commentNew = PodioComment::get_for('item', $item['item_id']); if (!isset($commentNew[0])) { $addLine = true; $options = array('silent' => true, 'hook' => false); $commentAttributes = array(); $commentAttributes['value'] = $item['item_created_by_comment']; PodioComment::create('item', $item['item_id'], $commentAttributes, $options); $commentEnd['value'] = "--------------------------------------------------------------"; PodioComment::create('item', $item['item_id'], $commentEnd, $options); $app = $appModel->findOne(array('queue_id' => "59c3066cb50088902f84b2ee", "new_app_id" => $item['new_app_id'])); if (isset($app['votes']) && !is_null($app['votes']) && is_array($app['votes'])) { foreach ($app['votes'] as $voteId) { $voteFields = Podio::get("/voting/item/" . $item['old_item_id'] . "/voting/$voteId/result?max_voters=1000"); if (isset($voteFields->body)) { $addLine = false; $podioComment = ""; $podioComment .= "**" . json_decode($voteFields->body)->voting->question . "**" . PHP_EOL; if (json_decode($voteFields->body)->voting->kind == "answer") { if (!is_null(json_decode($voteFields->body)->value)) { foreach (json_decode($voteFields->body)->voting->answers as $answer) { foreach ((array)json_decode($voteFields->body)->values as $id => $voteValue) { if ($id == $answer->answer_id) { $podioComment .= "* " . $answer->text . "(" . $voteValue->count . "): "; foreach ($voteValue->users as $user) { $podioComment .= "[" . $user->name . "](" . $user->link . ")" . ", "; } $podioComment = rtrim($podioComment, ", "); $podioComment .= PHP_EOL; } } } $commentAttributes = array(); $commentAttributes['value'] = $podioComment; PodioComment::create('item', $item['item_id'], $commentAttributes, $options); $commentEnd['value'] = "--------------------------------------------------------------"; PodioComment::create('item', $item['item_id'], $commentEnd, $options); } } elseif (json_decode($voteFields->body)->voting->kind == "fivestar") { $podioComment .= "Average of " . json_decode($voteFields->body)->average . " stars, " . json_decode($voteFields->body)->count . " votes" . PHP_EOL; if (!is_null(json_decode($voteFields->body)->value)) { foreach ((array)json_decode($voteFields->body)->values as $count => $voteValue) { $podioComment .= "* *" . $count; if ($count == 1) $podioComment .= " star*: "; else $podioComment .= " stars*: "; foreach ($voteValue->users as $user) { $podioComment .= "[" . $user->name . "](" . $user->link . ")" . ", "; } $podioComment = rtrim($podioComment, ", "); $podioComment .= PHP_EOL; } $commentAttributes = array(); $commentAttributes['value'] = $podioComment; PodioComment::create('item', $item['item_id'], $commentAttributes, $options); $commentEnd['value'] = "--------------------------------------------------------------"; PodioComment::create('item', $item['item_id'], $commentEnd, $options); } } } } } $limit = 100; $offset = 0; do { $attributes = array('limit' => $limit, 'offset' => $offset); $commentCollection = PodioComment::get_for('item', $item['old_item_id'], $attributes); $count = count($commentCollection); foreach ($commentCollection as $comment) { $commentAttributes = array(); switch (true) { //adding files case (count($comment->files) > 0 ? true : false): $temp = array(); foreach ($comment->files as $file) { $fileCopy = PodioFile::copy($file->file_id); array_push($temp, $fileCopy->file_id); } $commentAttributes['file_ids'] = $temp; break; // embed case (count($comment->embed) > 0 ? true : false): if ($comment->embed->original_url && $comment->embed->original_url != "") { $tempEmbed = PodioEmbed::create(array('url' => $comment->embed->original_url)); $commentAttributes['embed_id'] = $tempEmbed->embed_id; } break; //adding rich text only default: break; } $commentQuestion = ''; try { if ($comment->questions && count($comment->questions) > 0) { $tempArray = array(); foreach ($comment->questions[0]->answers as $value) { array_push($tempArray, strip_tags($value->question_option_id)); } foreach ($comment->questions[0]->options as $value) { $tempCount = array_count_values($tempArray); $commentQuestion .= strip_tags($value->text) . ' - '; if (isset($tempCount[$value->question_option_id])) { $temp = ($tempCount[$value->question_option_id]) . ' votes'; } else $temp = '0 votes'; $commentQuestion .= $temp . PHP_EOL; } $commentQuestion .= PHP_EOL; } if ($commentQuestion != "") $commentQuestion = PHP_EOL . $commentQuestion; } catch (Exception $e) { Log::error($e); } if ($addLine) { $commentEnd['value'] = "--------------------------------------------------------------"; PodioComment::create('item', $item['item_id'], $commentEnd, $options); } else $addLine = true; $commentAttributes['value'] = self::transformMentions($comment->rich_value) . $commentQuestion . $this->commentBy($comment); PodioComment::create('item', $item['item_id'], $commentAttributes, $options); } $offset += $limit; } while ($count > 99); } } catch (Exception $e) { print_r($e); exit; } $this->itemModel->update( array('_id' => new MongoId($item['_id'])), array('comment_status' => "new_completed") ); } print_r("Finished"); } } } public function commentBy($commentItem) { $comment = PHP_EOL . PHP_EOL; $comment .= ' *by [' . $commentItem->created_by->name . '](' . $commentItem->created_by->url . ')*'; $comment .= ' *on ' . date('Y-m-d H:i:s', $commentItem->created_on->getTimestamp()) . '* '; // CET return $comment; } public function taskCreatedByCommentTest($task) { $comment = PHP_EOL . PHP_EOL; $comment .= ' *Created by [' . $task->ref->created_by->name . '](' . $task->ref->created_by->url . ')*' . PHP_EOL . PHP_EOL; $comment .= ' *on ' . date('Y-m-d H:i:s', $task->created_on->getTimestamp()) . '* '; // CET return $comment; } public function taskCreatedByComment($task) { $comment = PHP_EOL . PHP_EOL; $comment .= ' *Created by [' . $task->ref->created_by->name . '](' . $task->ref->created_by->url . ')*' . PHP_EOL . PHP_EOL; $comment .= ' *on ' . date('Y-m-d H:i:s', $task->ref->created_on->getTimestamp()) . '* '; // CET return $comment; } public function postTest() { Log::info(Input::all()); } public function postPodioComment() { $filePath = public_path(); $filePath = $filePath . "/file_upload/"; echo $filePath; if ($_FILES['upload']) { Podio::setup('mastercard', 'xSESaNSp0ajfxt8KmQsDr84v3PmokkypMUz7sBxGAT1i4OmU27prgxwcIuatOPQC'); Podio::authenticate('password', array('username' => "jis.jose@phases.dk", 'password' => "JisPhases@123")); $file_ary = $this->reArrayFiles($_FILES['upload']); print_r($file_ary); foreach ($file_ary as $file) { // $filePath . $file['name']; move_uploaded_file($file['tmp_name'], $filePath . $file['name']); $this->uploadAndAddComment($filePath . $file['name'], $file['name'], 539150896); } } } public function reArrayFiles(&$file_post) { $file_ary = array(); try { $file_count = count($file_post['name']); $file_keys = array_keys($file_post); for ($i = 0; $i < $file_count; $i++) { foreach ($file_keys as $key) { $file_ary[$i][$key] = $file_post[$key][$i]; } } } catch (Exception $e) { Log::error($e); } return $file_ary; } private function uploadAndAddComment($file, $name, $itemID) { try { $attributes = array( 'value' => "Project document attached." ); $podioFileCreateResponse = PodioFile::upload($file, rtrim($name)); $attributes['file_ids'] = array($podioFileCreateResponse->file_id); PodioComment::create('item', $itemID, $attributes); // unlink($file); } catch (Exception $e) { Log::error($e); } } // https://podiocopy.phases.dk/test/continue-space public function getCheckSpace() { if ($this->authRepo->authenticateUser('59bc1958b50088fb7a756b3a')) { try { $space = PodioSpace::get(3013813); log::info($space); } catch (Exception $e) { log::error($e); } } } public function getAppItems() { $userId = "56bc202385810d000f3ba133"; if ($this->authRepo->authenticateUser($userId)) { try { echo "User authenticated"; //$refFlows = array(); $response = PodioApp::install(15003525, $attributes = array( "space_id" => 2365037, "features" => array('votings', 'items', 'integration', 'forms', 'filters', 'widgets') )); $flows = PodioFlow::get_flows('app', 15003525); foreach ($flows as $flow) { foreach ($flow['effects'] as $effect) { if (isset($effect['config'])) { // array_push($refFlows, $flow); $appFlow = PodioFlow::create("app", $response, $flow); if ($appFlow) { echo "yes"; } else { echo "no"; } } } } } catch (Exception $e) { echo '<pre>'; print_r($e); log::error($e); } exit; } else { echo "Not authenticated"; } } public function getResponse() { header('HTTP/1.1 200 OK'); echo "200"; } public function getAppUpdate() { echo "getAppItems"; echo "<pre>"; $userId = "555dce1d21b4d65a198b4567"; if ($this->authRepo->authenticateUser($userId)) { echo "User authenticated"; try { $resp = PodioAppField::get(12442339, 'contact'); echo $resp->field_id; print_r($resp); } catch (PodioNotFoundError $e) { $attributes = array("type" => 'app', 'config' => array( 'label' => 'Contact', 'visible' => true, 'delta' => 1, 'mapping' => NULL, 'default_value' => NULL, 'required' => false, 'description' => 'desc', 'settings' => array('referenceable_types' => array(12442257)) )); $resp = PodioAppField::create(12442339, $attributes); } } } public function getAppRel() { echo "getAppItems"; echo "<pre>"; $userId = "611e5ba0b7acb4477e388fc2"; if ($this->authRepo->authenticateUser($userId)) { echo "User authenticated"; $podioApp = PodioApp::get(22624162, $attributes = array()); dd($podioApp); $fieldRel = array(); foreach ($podioApp->fields as $field) { // echo $field->type."<br>"; if ($field->type == 'contact') { echo "app"; print_r($field->config); /* if (array_key_exists("apps", $field->config['settings'])) { $det = array('field_id' => $field->field_id); $det['config'] = array( 'label' => $field->config['label'], 'visible' => $field->config['visible'], 'delta' => $field->config['delta'], 'mapping' => $field->config['mapping'], 'default_value' => $field->config['default_value'], 'required' => $field->config['required'], 'description' => $field->config['description'] ); foreach ($field->config['settings']['apps'] as $appRel) { $det['relationApps'][] = array('app_id' => $appRel['app_id'], 'space_id' => $appRel['space_id']); } $fieldRel[] = $det; } */ } } // print_r($fieldRel); } } public function getComments() { echo "getComments"; echo "<pre>"; $userId = "555dce1d21b4d65a198b4567"; if ($this->authRepo->authenticateUser($userId)) { echo "User authenticated"; $itemID = 260944293; $options = array('silent' => true, 'hook' => false); $attributes = array('limit' => 1, 'offset' => 0); // $commentCollection = PodioComment::get_for('item', $itemID, $attributes); // print_r($commentCollection); $commentAttributes = array(); $commentAttributes['value'] = "Test comment"; // PodioComment::create('item', $itemID, $commentAttributes, $options); // echo "Rate Limit Remaining".Podio::rate_limit_remaining(); $resp = Podio::get("/comment/item/$itemID/", $attributes); // $resp = json_decode($resp->body); print_r($resp); // $commentCollection = PodioComment::get_for('item', $itemID, $attributes); // print_r($commentCollection); // echo "Rate Limit Remaining".Podio::rate_limit_remaining(); // $limit = 100; // $offset = 0; // do { // $attributes = array('limit' => $limit, 'offset' => $offset); // // $count = count($commentCollection); // } while ($count > 99); } } private function getItemRelation($podioItem, $oldItemID) { foreach ($podioItem->fields as $field) { if ($field->type == 'app') { foreach ($field->values as $value) { // print_r($value); echo $value->item_id; if (isset($value->item_id)) { $fieldRelations = array( 'field_id' => $field->field_id, 'ref_item_id' => $value->item_id, 'ref_app_id' => $value->app->app_id, ); print_r($fieldRelations); } } } } } // public function getUpdateItem() // { // echo "getAppItems"; // echo "<pre>"; // $userId = "555dce1d21b4d65a198b4567"; // if ($this->authRepo->authenticateUser($userId)) { // $options = array('hook' => false, 'silent' => true); // echo "User authenticated"; // $newRelation = array(); // $newRelation[] = 280138724; // $newRelation[] = 280138726; // $resp = PodioItem::update(280138610, // array('fields' => array('contact-2' => $newRelation)), $options); // print_r($resp); // } // } public function getCloneApp() { exit(); echo "getCloneApp"; echo "<pre>"; $userId = "555dce1d21b4d65a198b4567"; if ($this->authRepo->authenticateUser($userId)) { try { $response = PodioApp::install(12509317, $attributes = array( "space_id" => 3576359, "features" => array('votings', 'items', 'integration', 'flows', 'forms', 'filters', 'widgets') )); print_r($response); } catch (Exception $e) { print_r($e); } } } public function getTask() { echo "getTestCalculation" . PHP_EOL; echo "<pre>"; $userId = "555dce1d21b4d65a198b4567"; if ($this->authRepo->authenticateUser($userId)) { $taskCount = Podio::get("/task/app/8635367/count"); //$taskCount = json_decode($taskCount->body); print_r($taskCount); } } public function getTestCalculation($userId, $queueId) { // exit(); echo "getTestCalculation" . PHP_EOL; echo "<pre>"; $calculationRepo = new CalculationRepo(); $podioAppsModel = new PodioAppModel(); try { if ($this->authRepo->authenticateUser((string)$userId)) { $i = 0; $prevCount = 0; $count = 0; do { $i++; $apps = $podioAppsModel->find(array('queue_id' => (string)$queueId)); if ($count != $prevCount) $prevCount = $count; $count = 0; log::info("LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOP"); if ($apps) { foreach ($apps as $app) { $missingFields = $this->arrayDiff($app['fields'], $app['new_fields']); log::info($app['app_id']); log::debug($missingFields); $count += count($missingFields); $newFields = $app['new_fields']; $appFields = $app['fields']; try { foreach ($missingFields as $field) { if ($field['type'] == 'calculation') { if ($field['script_status'] != "updated") { Log::info("Inside new logic"); $newScript = $calculationRepo->getNewScript($app, $field['script'], null); // log::info($newScript); if ($newScript) { try { $attributes = array("type" => 'calculation', 'config' => array( 'label' => $field['label'], 'delta' => $field['delta'], 'settings' => array('script' => $newScript) )); if (isset($field['hidden'])) $attributes['hidden'] = $field['hidden']; $resp = PodioAppField::create($app['new_app_id'], $attributes); $newFields[] = array( "type" => 'calculation', 'label' => $field['label'], 'external_id' => $field['external_id'], 'field_id' => intval($resp) ); log::info("New Field Created:" . $resp); foreach ($appFields as $k => $appField) { if ($appField['field_id'] == $field['field_id']) { $appFields[$k]['script_status'] = "updated"; } } } catch (Exception $e) { foreach ($appFields as $k => $appField) { if ($appField['field_id'] == $field['field_id']) { $appFields[$k]['script_status'] = "error_on_update"; } } // Log::error($e); } } } } } } catch (Exception $e) { Log::error($e); } // log::info($newFields); $podioAppsModel->update( array('_id' => $app['_id']), array('fields' => $appFields, 'new_fields' => $newFields) ); } } if ($i > 1000) break; sleep(5); log::info("Missing Count: " . $count); log::info("Missing Prev Count: " . $prevCount); print_r("Missing Count: " . $count); print_r("Missing Prev Count: " . $prevCount); } while ($count > 0 && $prevCount != $count); Log::info('exiting do-while loop'); } } catch (Exception $e) { Log::error($e); log::info($app['app_id']); } } public function getCalculationFieldData($userId, $queueId) { $calculationRepo = new CalculationRepo(); $podioAppsModel = new PodioAppModel(); try { if ($this->authRepo->authenticateUser((string)$userId)) { $existing_field_config = PodioAppField::get(21467352, 176483052)->config; dd($existing_field_config); exit; $i = 0; $prevCount = 0; $count = 0; $i++; $apps = $podioAppsModel->find(array('queue_id' => (string)$queueId)); if ($count != $prevCount) $prevCount = $count; $count = 0; if ($apps) { foreach ($apps as $app) { echo "APP -> <b>" . $app['app_name'] . "</b><br>------------------" . "<br>"; // $missingFields = $this->arrayDiff($app['fields'], $app['new_fields']); //$count += count($missingFields); $newFields = $app['new_fields']; $appFields = $app['fields']; try { foreach ($appFields as $field) { if ($field['type'] == 'calculation') { $count++; $hidden = "NO"; // if($field['hidden']=="true") // $hidden = "YES"; $existing_field_config = PodioAppField::get($app['app_id'], $field['external_id'])->config; if ($existing_field_config['hidden'] == "true") $hidden = "YES"; echo "Field -> " . $field['label'] . "------------" . $hidden . "<br>"; $fcount = 0; if ($hidden == "YES") { foreach ($newFields as $newField) { if ($newField['type'] == 'calculation') { if ($field['label'] == $newField['label']) { echo "ENTERING......"; if ($fcount == 1) { $existing_new_field_config = PodioAppField::get($app['new_app_id'], $newField['field_id'])->config; $nhidden = "NO"; if ($existing_new_field_config['hidden'] == "true") $nhidden = "NEW FIELD YES"; echo "NewField -> " . $newField['label'] . "------------" . $nhidden . "<br>" . "<br>"; $existing_new_field_config['hidden'] = true; PodioAppField::update($app['new_app_id'], $newField['field_id'], $existing_new_field_config); } $fcount++; } } } } } } } catch (Exception $e) { Log::error($e); } } } echo $count; // if ($i > 1000) // break; } } catch (Exception $e) { print_r($e); Log::error($e); log::info($app['app_id']); } } private function arrayDiff($aArray1, $aArray2) { $aReturn = array(); foreach ($aArray1 as $mValue) { if ($this->inArrayCheck($aArray2, $mValue)) { $aReturn[] = $mValue; } } return $aReturn; } private function inArrayCheck($aArray2, $subArray) { foreach ($aArray2 as $mValue) { if ($mValue['type'] == $subArray['type'] && $mValue['external_id'] == $subArray['external_id']) return false; } return true; } private function arrayRecursiveDiff($aArray1, $aArray2, $key) { $aReturn = array(); foreach ($aArray1 as $mKey => $mValue) { if (array_key_exists($mKey, $aArray2)) { if (is_array($mValue)) { $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey], $key); if (count($aRecursiveDiff) && array_key_exists($key, $aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; } } else { if ($key == $mKey && $mValue != $aArray2[$mKey]) { $aReturn[$mKey] = $mValue; } } } else { $aReturn[$mKey] = $mValue; } } return $aReturn; } public function getTestRegex() { $expression = "(field_\\d+)"; $expression1 = "(out_\\d+_\\d+)"; $string = "@[F NAME](field_95655589)+\" \"+@[L NAME](field_95655590)"; echo "<pre>"; if (preg_match_all($expression, $string, $matches)) { echo count($matches[0]) . " matches found"; print_r($matches[0]); } } public function getCopySpaceContacts() { exit(); echo "getCopySpaceContacts" . PHP_EOL; echo "<pre>"; $userId = "555dce1d21b4d65a198b4567"; if ($this->authRepo->authenticateUser($userId)) { $space_id = 3520964; $targetSapce = 3588942; $contacts = PodioContact::get_for_space($space_id, $attributes = array('contact_type' => 'space')); if ($contacts) { foreach ($contacts as $contact) { $attributes = array( 'name' => $contact->name, 'mail' => $contact->mail, 'phone' => $contact->phone, 'link' => $contact->link, 'title' => $contact->title, 'organization' => $contact->organization, 'image' => $contact->image ); $resp = PodioContact::create($targetSapce, $attributes); } } } } public function getField() { echo "<pre>"; $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { $sourceAppId = 21272100; $fieldId = 174638785; try { $field = PodioAppField::get($sourceAppId, $fieldId); print_r($field); } catch (Exception $e) { return 'false'; } } } public function getSaveMissingItems() { $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { echo "<pre>"; $podioAppsModel = new PodioAppModel(); $app = $podioAppsModel->find(array( 'queue_id' => '5b578d41b50088da227b23c6', 'new_app_id' => 21272100 ), 1); try { $itemRepo = new ItemRepo(); // get all the item from the new app $limit = 50; $offset = 0; do { LogAll::LogMessage($app['queue_id'], "message", "saveItemsInApp : limit" . $limit . ", offset:" . $offset, ""); $continue = false; $count = 0; $attributes = array( 'sort_desc' => true, 'limit' => $limit, 'offset' => $offset ); $itemCollection = PodioItem::filter($app['new_app_id'], $attributes, $options = array()); if ($itemCollection) { PodioDBSession::updateRateLimit($app['user']); $count = count($itemCollection); foreach ($itemCollection as $item) { $itemID = $item->item_id; $oldItemID = str_replace("share_", "", $item->external_id); $itemRepo->saveItemToDB($app, $itemID, $oldItemID); } if ($count > 0) { $continue = true; PodioDBSession::updateRateLimitGeneral($app['user']); } $offset += $limit; } } while ($continue && $count >= $limit); } catch (Exception $e) { echo "<pre>"; print_r($e); exit; } } } public function getSaveMissingItemRelation() { $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { echo "<pre>"; $podioAppsModel = new PodioAppModel(); $app = $podioAppsModel->find(array( 'queue_id' => '5b578d41b50088da227b23c6', 'new_app_id' => 21272100 ), 1); try { $itemRepo = new ItemRepo(); $itemModel = new ItemModel(); $items = $itemModel->find(array( 'queue_id' => $app['queue_id'], 'new_app_id' => 21272100, 'save_item_relation_status' => "not_saved" )); if ($items) { // check rate limit between 10 items $limitCheck = 0; foreach ($items as $item) { $oldItemID = $item['old_item_id']; $oldPodioItem = PodioItem::get($oldItemID); $itemRepo->saveItemRelation($oldPodioItem, $item['_id']); if ($limitCheck++ % 10 == 0) { PodioDBSession::updateRateLimitGeneral($app['user']); if (PodioDBSession::getRateLimitGenRemains($app['user']) <= 1000) { // $app['item_count']) *100 print_r("RateLimit EXIT"); exit(); } } } PodioDBSession::updateRateLimitGeneral($app['user']); } } catch (Exception $e) { echo "<pre>"; print_r($e); exit; } } } public function getUpdateItemRelation() { $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { echo "<pre>"; $podioAppsModel = new PodioAppModel(); $itemRepo = new ItemRepo(); $app = $podioAppsModel->find(array( 'queue_id' => '5b578d41b50088da227b23c6', 'new_app_id' => 21272100 ), 1); $options = array('hook' => false, 'silent' => true); $items = $this->itemModel->find(array('new_app_id' => $app['new_app_id'], 'queue_id' => $app['queue_id'])); if ($items) { foreach ($items as $item) { if ($item['field_relations'] && count($item['field_relations'])) { foreach ($item['field_relations'] as $key => $relations) { if (PodioDBSession::getRateLimitRemains($app['user']) <= 100) { exit(); } $newRelation = array(); foreach ($relations as $rel) { $newItemID = $itemRepo->getNewRelationItem($item['queue_id'], $rel['ref_item_id'], $rel['ref_app_id']); if ($newItemID) $newRelation[] = $newItemID; } $newFieldId = $itemRepo->getNewAppField($app, $key); $externalId = ($newFieldId) ? $newFieldId : $key; try { if ($externalId && count($newRelation)) { $resp = PodioItem::update( $item['item_id'], array('fields' => array((int)$externalId => $newRelation)), $options ); PodioDBSession::updateRateLimit($app['user']); } } catch (Exception $e) { $resp = PodioItem::update( $item['item_id'], array('fields' => array((int)$externalId => null)), $options ); PodioDBSession::updateRateLimit($app['user']); // print_r($e); // exit; } } } $this->itemModel->update(array('_id' => $item['_id']), array("ref_update_status" => "updated2")); } } } } public function getCount() { $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { $sourceAppId = 20001050; $fieldId = 170859142; try { $count = PodioItem::get(897317574); echo "<pre>"; print_r($count->fields); exit; } catch (Exception $e) { return 'false'; } } } public function getTestMongo() { echo "<pre>"; $podioAppsModel = new PodioAppModel(); $originalRelApp = $podioAppsModel->find(array('app_id' => 20001050, 'queue_id' => "5b578d41b50088da227b23c6"), 1); print_r($originalRelApp); } public function getApps() { echo "<pre>"; $userId = "5b354e6db5008817056dd626"; if ($this->authRepo->authenticateUser($userId)) { $sourceAppId = 21272100; try { $field = PodioAppField::get($sourceAppId, 174638785); print_r($field); } catch (Exception $e) { return 'false'; } } } public function getRatelimit() { $options = array('silent' => true, 'hook' => false); $userId = "556c4e4a21b4d648635ce70d"; if ($this->authRepo->authenticateUser($userId)) { echo "<pre>"; $taskCount = Podio::get("/task/app/8635367/count"); log::info(Podio::rate_limit_remaining()); print_r("HII"); print_r($taskCount); print_r(Podio::rate_limit_remaining()); } } public static function transformMentions($string) { return preg_replace('/@\[(.*?)]\([\w]+:([\w]+)\)/i', '@[$1](https://podio.com/users/$2)', $string); } public function getMailTest() { Mail::send('emails.completed', array("name" => "jis"), function ($message) { $message->to("jis.jose@phases.dk") ->subject('Podio copy is complete'); $message->from(Config::$CONTACT_US_EMAIL, Config::$CONTACT_US_EMAIL_NAME); }); } public function getDestinationOrganizationRights() { $authRepo = new AuthRepository(); $authRepo->authenticateUser('573103eeb50088581ec7b081'); $orgId = 1131856; $checkRightsRepo = new CheckRightsRepo(); $resp = $checkRightsRepo->checkDestinationOrganizationRights($orgId); echo "<pre>"; print_r($resp); exit(); if ($resp == 'free') { return array( "status" => "prevent", "message" => "You are a Light user in the destination organization." . "<br/>You need to be an Admin or Regular access for the data copy to work properly." ); } else { echo "<pre>"; print_r($resp); exit(); if (isset($resp['userLimit'])) { $message = "The user limit of the selected organization is " . $resp['userLimit'] . "." . "<br/>If the total number of users from source and the destination organization exceeds this limit, the copy will still happen, but it will not include all the users and the copied tasks will be assigned to yourself."; return array("status" => "warning", "data" => $resp, "message" => $message); } else { $message = null; return array("status" => "no_message", "data" => $resp, "message" => $message); } } } public function getTestCopy() { $userID = "57f237eab500889973a0df54"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { //// echo "<pre>"; // $resp = Podio::get("/item/341940553"); // echo($resp->body); // echo "<br/><br/>"; // echo "Getting app"; $app = PodioApp::get(16873908, $attributes = array()); echo "<pre>"; echo($app); exit(); // $count= PodioItem::get_count( 16094926 ); // echo $count; // $resp = Podio::get("/item/438220855"); // echo "<pre>"; // echo($resp->body); // //// $resp = Podio::get("/space/4306714/member/3195200/v2"); //// echo $resp->body; // //// 9412622 9412618 // $appMoveRepo = new AppMoveRepo(); // $podioAppsModel = new PodioAppModel(); // $app = $podioAppsModel->find(array('app_id' => 13579093, 'queue_id' => "576849b2b50088c26ca5686e" // ), 1); // $appMoveRepo->copyCloneErrorItems($app); // $appMoveRepo->saveItemsRelationTest($app); // $appMoveRepo->copyItemCommentsTest($app); // $appMoveRepo->copyItemTasksTest($app); // $appMoveRepo->updateItemReferencesTest($app); } } public function getTestTasks() { $userID = "5783fe18b50088120bab029a"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { // $item = PodioItem::get_by_app_item_id(16300911, 300); // print_r($item); // 453056441 new item // $itemID = 428916481; task count=3 // exit(); // $resp = PodioItem::get(453056183); // echo($resp); // exit(); // $oldItemID = 111117119; $item_id = 453055347; echo "<br/><br/>"; echo "oldItemID $oldItemID item_id $item_id"; $resp = Podio::get("/task/item/" . $oldItemID . "/count"); $json = json_decode($resp->body); $oldCompletedCount = $json->count; echo "<br/>"; echo "oldCompletedCount $oldCompletedCount"; $resp = Podio::get("/task/item/" . $item_id . "/count"); $json = json_decode($resp->body); $currentCompletedCount = $json->count; echo "<br/>"; echo "currentCompletedCount $currentCompletedCount"; if ($oldCompletedCount != $currentCompletedCount) { // need to copy all } else { $attributes = array("reference" => "item:" . $oldItemID); $tasks = PodioTask::get_all($attributes); $oldCount = count($tasks); echo "<br/>"; echo "oldCount $oldCount"; $attributes = array("reference" => "item:" . $item_id); $tasks = PodioTask::get_all($attributes); $currentCount = count($tasks); echo "<br/>"; echo "currentCount $currentCount"; } exit(); // $queue = "578d1da8b500880151d273ca"; // $itemModel = new ItemModel(); // $items = $itemModel->find(array('queue_id' => $queue, // 'task_status' => array('$ne' => 'completed'))); // if ($items) { // foreach ($items as $item) { // $this->copyItemTask($item); // } // } } } private function copyItemTask($item) { $queue = "578d1da8b500880151d273ca"; $userID = "5783fe18b50088120bab029a"; try { $oldItemID = $item['old_item_id']; $item_id = $item['item_id']; echo "<br/><br/>"; echo "oldItemID $oldItemID item_id $item_id"; $resp = Podio::get("/task/item/" . $oldItemID . "/count"); $json = json_decode($resp->body); $oldCompletedCount = $json->count; echo "<br/>"; echo "oldCompletedCount $oldCompletedCount"; $resp = Podio::get("/task/item/" . $item_id . "/count"); $json = json_decode($resp->body); $currentCompletedCount = $json->count; echo "<br/>"; echo "currentCompletedCount $currentCompletedCount"; if ($oldCompletedCount != $currentCompletedCount) { // need to copy all $this->copyTasks($item, $userID, true); } else { $attributes = array("reference" => "item:" . $oldItemID); $tasks = PodioTask::get_all($attributes); $oldCount = count($tasks); echo "<br/>"; echo "oldCount $oldCount"; $attributes = array("reference" => "item:" . $item_id); $tasks = PodioTask::get_all($attributes); $currentCount = count($tasks); echo "<br/>"; echo "currentCount $currentCount"; if ($oldCount != $currentCount) { // copy completed task only $this->copyTasks($item, $userID, false); } else { $itemModel = new ItemModel(); $itemModel->update( array('_id' => new MongoId($item['_id'])), array('task_status' => "completed", "task_debug" => true, "no_task" => true) ); } } } catch (Exception $e) { LogAll::LogMessage($queue, "error", "copyItemTask", $e); } } private function copyTasks($item, $user, $copyAll) { $itemModel = new ItemModel(); $attributes = array("reference" => "item:" . $item['old_item_id']); $tasks = PodioTask::get_all($attributes); foreach ($tasks as $task) { $this->createTask($task, $copyAll, $item, $user); } $itemModel->update( array('_id' => new MongoId($item['_id'])), array('task_status' => "completed", "task_debug" => true, "copy_all" => $copyAll) ); } public function createTask($task, $copyAll, $item, $user) { $queue = "578d1da8b500880151d273ca"; try { $taskTempModel = new TaskTempModel(); $options = array('silent' => true, 'hook' => false); $commentAttributes = array(); $comment = $this->taskCreatedByComment($task); $taskStatus = $task->status; if ($copyAll || $taskStatus == 'completed') { $attributes = array( "responsible" => $task->responsible->user_id, "group" => $task->group, "text" => $task->text, "description" => $task->description, "private" => $task->private, "due_on" => $task->due_on ? $task->due_on->format('Y-m-d H:i:s') : null, // date('Y-m-d H:i:s', $commentItem->created_on->getTimestamp()) "due_date" => $task->due_date ? $task->due_date : null, // $task->due_date "due_time" => $task->due_time ? $task->due_time : null, //$task->due_time ); $resp = PodioTask::create_for("item", $item['item_id'], $attributes, $options); $commentAttributes['value'] = $comment; PodioComment::create('task', $resp->task_id, $commentAttributes, $options); PodioDBSession::updateRateLimit($user); if ($taskStatus == 'completed') { PodioTask::complete($resp->task_id); } $taskTempModel->create(array( 'queue' => $queue, 'old_item_id' => $item['old_item_id'], "item_id" => $item['item_id'], 'old_task_id' => $task->task_id, "task_id" => $resp->task_id )); } } catch (Exception $e) { LogAll::LogMessage($queue, "error", "copyItemTask", $e); } } public function getCheckTask() { $userID = "579f327fb500880d711b23a6"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { // $task = PodioTask::get(51446318); //// print_r($resp); // echo $task->responsible->user_id; // $this->checkTasks(); // exit(); // $this->copyTask(); // $this->checkUsers(); // $this->copyWSTasks(); exit(); $podioWorkSpaceModel = new WorkSpaceModel(); $space = $podioWorkSpaceModel->find(array('target_space_id' => 4793599), 1); echo $userID = (string)$space['user']; $repo = new WorkSpaceMoveRepo(); $repo->updateSpaceTasksTest($space); } } private function checkUsers() { try { echo "<pre>"; // $spaces = array(6960055, 6960054); // $spaces = array(6894331, 6894205, 5625495, 5625543); $spaces = array(7075133, 4748145, 4215416, 4700762, 7046247, 7035357, 7075013, 7075098, 7080568, 7075023); $userArray = array(); foreach ($spaces as $space) { $spaceMembers = PodioSpaceMember::get_all($space); foreach ($spaceMembers as $contact) { if (!in_array($contact->profile->user_id, $userArray)) { echo $contact->user->mail . "<br>"; array_push($userArray, $contact->profile->user_id); } } } } catch (Exception $e) { dd($e); } } public function getCheckStatus() { $userID = "555dce1d21b4d65a198b4567"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $attributes = array( 'sort_desc' => false, 'limit' => 100, 'offset' => 0 ); $podioStreams = PodioStreamObject::get_for_space(4747086, $attributes); $count = count($podioStreams); foreach ($podioStreams as $podioStream) { if ($podioStream->type == 'status') { if ($podioStream->data['embed']) { echo $podioStream->data['embed']['original_url']; // $tempEmbed = PodioEmbed::create(array('url' => $podioStream->data['embed']->original_url)); // $attr['embed_id'] = $tempEmbed->embed_id; } } } } } private function checkUserRoles() { $userIDs = array(); $spaceMembers = PodioSpaceMember::get_all(4793599); foreach ($spaceMembers as $contact) { $userIDs[] = $contact->profile->user_id; } } private function checkTasks() { // $total=0; // $limit = 50; // $offset = 0; // do { // // $attributes = array("reference" => "space:1500980", "limit" => $limit, "offset" => $offset); // $tasks = PodioTask::get_all($attributes); // foreach ($tasks as $task) { // echo "<br/>"; // echo $task->responsible->user_id; // } // $count = count($tasks); // echo "Total $count tasks"; // $offset += $limit; // $total+=$count; // } while ($count == $limit); // // echo "Total $total tasks"; $attributes = array("reference" => "space:4793599"); $tasks = PodioTask::get_all($attributes); foreach ($tasks as $task) { echo "<br/>"; echo $task->responsible->user_id; PodioTask::delete($task->task_id); } $count = count($tasks); echo "Total $count tasks"; } private function copyTask() { $options = array('silent' => true, 'hook' => false); $task = PodioTask::get(54111096); try { $commentAttributes = array(); $taskStatus = $task->status; $responsible = $task->responsible->user_id; echo "<br/> responsible $responsible"; $fileArray = array(); foreach ($task->files as $file) { $fileCopy = PodioFile::copy($file->file_id); array_push($fileArray, $fileCopy->file_id); } $attributes = array( "responsible" => $responsible, "group" => $task->group, "text" => $task->text, "description" => $task->description, "private" => $task->private, "due_on" => $task->due_on ? $task->due_on->format('Y-m-d H:i:s') : null, "due_date" => $task->due_date ? $task->due_date : null, // $task->due_date "due_time" => $task->due_time ? $task->due_time : null, //$task->due_time "file_ids" => $fileArray ); // todo Rate-limited $resp = PodioTask::create_for("space", 2365037, $attributes, $options); try { $ItemRepo = new ItemRepo(); // $ItemRepo->copyTaskComments($task->task_id, $resp->task_id); } catch (Exception $e) { LogAll::LogMessage("test", "error", "createTask", $e); } if ($taskStatus == 'completed') { PodioTask::complete($resp->task_id); } } catch (Exception $e) { LogAll::LogMessage("test", "error", "", $e); //Log::error($e); } } private function copyWSTasks() { $userMdl = new User(); $userID = "579f327fb500880d711b23a6"; $user = $userMdl->findOne(array('_id' => new MongoId($userID))); $podioUserID = intval($user['podioUserID']); $options = array('silent' => true, 'hook' => false); $userIDs = array(); $spaceMembers = PodioSpaceMember::get_all(4793599); foreach ($spaceMembers as $contact) { $userIDs[] = $contact->profile->user_id; } $limit = 100; $offset = 0; do { $attributes = array("reference" => "space:1500980", "limit" => $limit, "offset" => $offset); $tasks = PodioTask::get_all($attributes); $count = 0; foreach ($tasks as $task) { try { $commentAttributes = array(); // $comment = $this->taskCreatedByComment($task); $taskStatus = $task->status; $responsible = $task->responsible->user_id; echo "<br/> responsible $responsible"; if (!in_array($responsible, $userIDs)) { echo "<br/> responsible $responsible is not in space"; $responsible = $podioUserID; } $fileArray = array(); foreach ($task->files as $file) { $fileCopy = PodioFile::copy($file->file_id); array_push($fileArray, $fileCopy->file_id); } $attributes = array( "responsible" => $responsible, "group" => $task->group, "text" => $task->text, "description" => $task->description, "private" => $task->private, "due_on" => $task->due_on ? $task->due_on->format('Y-m-d H:i:s') : null, "due_date" => $task->due_date ? $task->due_date : null, // $task->due_date "due_time" => $task->due_time ? $task->due_time : null, //$task->due_time "file_ids" => $fileArray ); // todo Rate-limited $resp = PodioTask::create_for("space", 4793599, $attributes, $options); // $commentAttributes['value'] = $comment; // PodioComment::create('task', $resp->task_id, $commentAttributes, $options); if ($taskStatus == 'completed') { PodioTask::complete($resp->task_id); } } catch (Exception $e) { LogAll::LogMessage("test", "error", "", $e); //Log::error($e); } } $count = count($tasks); $offset += $limit; } while ($count == $limit); } public function getCopyWorkflow() { // $userID = "556c4e4a21b4d648635ce70d"; // $authRepo = new AuthRepository(); // if ($authRepo->authenticateUser($userID)) { // $attributes = array( // 'config' => array( // 'conditions' => array() // ), // "effects" => array(array( // "attributes" => array(array( // 'attribute_id' => "comment.value", // 'label' => "Comment", // 'required' => true, 'substitutions' => array(), // 'type' => "text", 'value' => "Hahahahah" // )), // 'type' => "comment.create", // )), // 'name' => 'Niv', // 'type' => 'item.create' // ); //// try { //// $resp = Podio::post("/flow/app/15051445/", $attributes); //// } catch (Exception $e) { //// exit; //// } // print_r($attributes); // } // exit; $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); $appId = 10942106; $newAppId = 18147663; if ($authRepo->authenticateUser($userID)) { Podio::set_debug(true); $flows = PodioFlow::get_flows('app', $appId); echo "<pre>"; foreach ($flows as $flow) { $newFlow = array(); // $newFlow['type'] = $flow['type']; $newFlow['name'] = $flow['name']; $newFlow['config'] = array(); if (!empty($flow['config']['field_ids'])) { if (is_array($flow['config']['field_ids']) or ($flow['config']['field_ids'] instanceof Traversable)) { $newFlow['config']['field_ids'] = array(); foreach ($flow['config']['field_ids'] as $fieldId) { $field = PodioAppField::get($appId, $fieldId); $externalId = $field->external_id; $field = PodioAppField::get($newAppId, $externalId); $fieldId = $field->field_id; array_push($newFlow['config']['field_ids'], $fieldId); } } } if (!empty($flow['config']['conditions'])) { if (is_array($flow['config']['conditions']) or ($flow['config']['conditions'] instanceof Traversable)) { $newFlow['config']['conditions'] = array(); foreach ($flow['config']['conditions'] as $condition) { $conditionField = $condition['field_id']; $field = PodioAppField::get($appId, $conditionField); $externalId = $field->external_id; $field = PodioAppField::get($newAppId, $externalId); $fieldId = $field->field_id; $condition['field_id'] = $fieldId; array_push($newFlow['config']['conditions'], $condition); } } } $newFlow['effects'] = array(); foreach ($flow['effects'] as $effect) { $newEffect = array(); $newEffect['type'] = $effect['type']; $newEffect['attributes'] = $effect['attributes']; foreach ($newEffect['attributes'] as $arrayIndex => $attribute) { foreach ($attribute as $index => $value) if ($value == "" || (is_array($value) && count($value) == 0)) { if ($index == "nullable" || $index == "required") $newEffect['attributes'][$arrayIndex][$index] = 0; elseif ($index != "substitutions") unset($newEffect['attributes'][$arrayIndex][$index]); } } $newEffect['attributes'] = array_values($newEffect['attributes']); if (array_key_exists('config', $effect) && $effect['config'] != null) { $newEffect['config'] = $effect['config']; $oldRefAppId = ""; print_r($newEffect); if (is_array($newEffect['config'])) { $oldRefAppId = $newEffect['config']['app']['app_id']; $oldRefFieldId = $newEffect['config']['field']['field_id']; $newAppId = 1234; $newFieldId = 2345; $newEffect['config']['field']['config']['settings']['referenced_apps'][0]['app_id'] = $newAppId; $newEffect['config']['field']['config']['settings']['referenceable_types'][0] = $newAppId; } } array_push($newFlow['effects'], $newEffect); // break; } $newFlow = array_filter($newFlow); // print_r($newFlow); exit; try { Podio::set_debug(true); // $resp = Podio::post("/flow/app/15051445/", $attributes); // $resp = Podio::put("/flow/1114290", $newFlow); $resp = PodioFlow::update(1114290, $newFlow); // $resp = PodioFlow::create('app', $newAppId, $newFlow); } catch (Exception $e) { log::error($e); print_r($e); exit(); } } } else { echo "Auth Failed"; } } public function myFunction($value, $key) { echo "The key" . $key . " has the value $value<br>"; } public function getTestTiles() { $userID = "556c4e4a21b4d648635ce70d"; $newWSid = 4344475; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { try { $widgets = PodioWidget::get_for('space', 4344480); $widgetsNew = PodioWidget::get_for('space', 4335070); foreach ($widgetsNew as $newWidget) { PodioWidget::delete("$newWidget->widget_id"); } $allowedtypes = array("link", "text", "files", "events", "tasks", "image"); foreach ($widgets as $widget) { $attributes = array("type" => $widget->type, "title" => $widget->title, "config" => $widget->config); switch ($widget->type) { case "image": $oldFile = $widget->config['file_id']; $fileID = PodioFile::copy($oldFile); $attributes['config']['file_id'] = $fileID->file_id; break; } print_r($widget->type); echo "<br>"; // if (in_array($widget->type, $allowedtypes)) { try { Podio::post("/widget/$widget->widget_id/clone", array("type" => "space", "id" => 4335070)); } catch (Exception $e) { } // } } $response = PodioApp::install(18120835, $attributes = array( "space_id" => 4335070, "features" => array('votings', 'layout', 'items', 'integration', 'flows', 'forms', 'filters', 'widgets') )); } catch (Exception $e) { print_r($e); } } } public function getViews() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); $app_id = 15051449; //16930063; 18234480 echo "<pre>"; if ($authRepo->authenticateUser($userID)) { try { $views = Podio::get("/view/app/{$app_id}/")->json_body(); foreach ($views as $view) { unset($view['view_id']); unset($view['created_by']); unset($view['created_on']); unset($view['filter_id']); unset($view['groupings']); $view = array_filter($view); if (isset($view['grouping']) && !empty($view['grouping'])) { if (isset($view['grouping']['value']) && !is_numeric($view['grouping']['value'])) { foreach ($view['filters'] as $k => $filter) { if (isset($filter['key']) && is_numeric($filter['key'])) { unset($view['filters'][$k]); } } PodioView::create(18365478, $view); } } } } catch (Exception $e) { print_r($e); } } } public function getCloneTest() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { try { $response = PodioApp::install(18365456, $attributes = array( "space_id" => 4344480, "features" => array('views', 'integration', 'forms', 'widgets') )); } catch (Exception $e) { print_r($e); } } } public function getTestFile() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { try { $podioAttributes = array('file_ids' => array()); $response = PodioItem::update(388518396, $podioAttributes, array('silent' => true)); } catch (Exception $e) { print_r($e); } } } public function authenticateUser($userID = null) { $podioUserID = null; if (!$userID) { if (Auth::user()->podioUserID) { $podioUserID = intval(Auth::user()->podioUserID); $userID = Auth::user()->id; } } else { $user = $this->user->findOne(array('_id' => new MongoId($userID))); if (!$user) return false; $podioUserID = intval($user['podioUserID']); } if ($podioUserID) { // podio setup $this->setupPodio(); Podio::$auth_type = array( "type" => "password", "podioUserID" => $podioUserID ); $podioDBSession = new PodioDBSession(); Podio::$oauth = $podioDBSession->get(Podio::$auth_type); if (Podio::is_authenticated()) { try { PodioUserStatus::get(); PodioDBSession::updateRateLimitGeneral($userID); return true; } catch (Exception $e) { Log::error("Podio is authenticated but get user details return an error podio UserID: " . $podioUserID); Log::error($e); return false; } } else { return false; } } return false; } private function setupPodio() { Podio::setup( Config::$PODIO_CLIENT_ID, Config::$PODIO_CLIENT_SECRET, array('session_manager' => 'PodioDBSession') ); } public function getAddMembers() { echo "<pre>"; $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { try { $workspaceNames = array( 'https://podio.com/citrix/audio-bridge', 'https://podio.com/citrix/audio-connectivity-improvements', 'https://podio.com/citrix/asc-350-40', 'https://podio.com/citrix/ce-housefile-activity', 'https://podio.com/citrix/ce-webinars', 'https://podio.com/citrix/clean-slate-implementation', 'https://podio.com/citrix/client-services-key-csm-westcentral', 'https://podio.com/citrix/cloud-based-recording', 'https://podio.com/citrix/content-program', 'https://podio.com/citrix/customer-care-wheel-winners', 'https://podio.com/citrix/datacom-clean-implementation-external', 'https://podio.com/citrix/demograph', 'https://podio.com/citrix/callout', 'https://podio.com/citrix/emea-demand-generation-dwa', 'https://podio.com/citrix/testing', 'https://podio.com/citrix/marketing-services', 'https://podio.com/citrix/emeamarketingloc', 'https://podio.com/citrix/emeaapac-marketing-automation', 'https://podio.com/citrix/enablement-tnps', 'https://podio.com/citrix/engagement-mktg-access-lob', 'https://podio.com/citrix/engineering-ka-all', 'https://podio.com/citrix/engineering-ka-management', 'https://podio.com/citrix/ka-platform-management', 'https://podio.com/citrix/facilities-locations', 'https://podio.com/citrix/g2m-cx-team', 'https://podio.com/citrix/engagement-channel', 'https://podio.com/citrix/getgo-inin-telecom', 'https://podio.com/citrix/osd-emea-systems-engineers', 'https://podio.com/citrix/goforward-march-2016-session-2', 'https://podio.com/citrix/gotoassist', 'https://podio.com/citrix/hackweek-2013-cohorts-teams', 'https://podio.com/citrix/hack-week-2013-demo-videos', 'https://podio.com/citrix/hack-week-2013-organizers-only', 'https://podio.com/citrix/hack-week-2013-santa-barbara1', 'https://podio.com/citrix/hack-week-2014', 'https://podio.com/citrix/hack-week-2014-bangalore', 'https://podio.com/citrix/hack-week-2014-copenhagen', 'https://podio.com/citrix/hack-week-2014-dresden', 'https://podio.com/citrix/hack-week-2014-jersey-city', 'https://podio.com/citrix/hack-week-2014-karlsruhe', 'https://podio.com/citrix/hack-week-2014-kimayas-cohort', 'https://podio.com/citrix/hack-week-2014-raleigh', 'https://podio.com/citrix/hack-week-2014-san-francisco', 'https://podio.com/citrix/hack-week-2014-santa-barbara', 'https://podio.com/citrix/hack-week-2014-demo-day', 'https://podio.com/citrix/hack-week-2015', 'https://podio.com/citrix/hack-week-2015-bangalore', 'https://podio.com/citrix/hack-week-2015-copenhagen', 'https://podio.com/citrix/hack-week-2015-dresden', 'https://podio.com/citrix/hack-week-2015-jersey-city', 'https://podio.com/citrix/hack-week-2015-karlsruhe', 'https://podio.com/citrix/hack-week-2015-raleighftl', 'https://podio.com/citrix/hack-week-2015-san-francisco', 'https://podio.com/citrix/hack-week-2015-santa-barbara', 'https://podio.com/citrix/hack-week-2016', 'https://podio.com/citrix/hack-week-2016-bangalore', 'https://podio.com/citrix/hack-week-2016-dresden', 'https://podio.com/citrix/hack-week-2016-karlsruhe', 'https://podio.com/citrix/hack-week-2016-needham', 'https://podio.com/citrix/hack-week-2016-san-francisco', 'https://podio.com/citrix/hack-week-2016-santa-barbara', 'https://podio.com/citrix/hackweek-2013-ideas', 'https://podio.com/citrix/on-demand-support-podio-site', 'https://podio.com/citrix/internet-of-things', 'https://podio.com/citrix/iot-star-trek-experience-2015', 'https://podio.com/citrix/ka-recruiting-forms-mjukyu', 'https://podio.com/citrix/lic', 'https://podio.com/citrix/osd---delta', 'https://podio.com/citrix/live-training-data', 'https://podio.com/citrix/outbound-training', 'https://podio.com/citrix/marketing-ops-project-management', 'https://podio.com/citrix/marketo-migration', 'https://podio.com/citrix/mobile-matters', 'https://podio.com/citrix/saas-tech-ops', 'https://podio.com/citrix/mobility-apps-ops-ges', 'https://podio.com/citrix/ops-managers', 'https://podio.com/citrix/opssrmgmt', 'https://podio.com/citrix/mobility-apps-techops-voice-managers', 'https://podio.com/citrix/saas-platform-ecosystem', 'https://podio.com/citrix/saas-platform-services', 'https://podio.com/citrix/one-commerce-phase-1', 'https://podio.com/citrix/multimedia-conference-rooms', 'https://podio.com/citrix/saasnps', 'https://podio.com/citrix/nsg-prod-isp-inventory', 'https://podio.com/citrix/certs-expiring-in-may15-verisign-verizon', 'https://podio.com/citrix/onlinelearning', 'https://podio.com/citrix/openvoice', 'https://podio.com/citrix/ops-automation', 'https://podio.com/citrix/outbound-customer-care', 'https://podio.com/citrix/podio-feature-wishlist', 'https://podio.com/citrix/presence-program', 'https://podio.com/citrix/private-test-jobx', 'https://podio.com/citrix/product-operations-communications-cloud', 'https://podio.com/citrix/professional-services', 'https://podio.com/citrix/ecrm-and-marketing-automation-collaboration', 'https://podio.com/citrix/project-monarch-marketing-2-end-state', 'https://podio.com/citrix/rbe-and-incentive-planning', 'https://podio.com/citrix/reconciliation-billingentitlement', 'https://podio.com/citrix/research-group', 'https://podio.com/citrix/resource', 'https://podio.com/citrix/saas-access-core-team', 'https://podio.com/citrix/saas-agile-best-practices', 'https://podio.com/citrix/lifecycle-planning', 'https://podio.com/citrix/saas-pmo-internal', 'https://podio.com/citrix/product-marketing', 'https://podio.com/citrix/setsale-platform', 'https://podio.com/citrix/smo', 'https://podio.com/citrix/mobility-apps-readiness-team-space', 'https://podio.com/citrix/ss-usability-and-feedback', 'https://podio.com/citrix/star-trek-experience', 'https://podio.com/citrix/teamawesome', 'https://podio.com/citrix/ukworkspace', 'https://podio.com/citrix/unified-funnel-marketing', 'https://podio.com/citrix/support-center-improvements', 'https://podio.com/citrix/support-research', 'https://podio.com/citrix/video-codec-team', 'https://podio.com/citrix/walkme-development', 'https://podio.com/citrix/wfm', 'https://podio.com/citrix/global-upgrade-info-hub', 'https://podio.com/citrix/inbound-care-wfm' ); $spaceId = array(); foreach ($workspaceNames as $url) { $space = PodioSpace::get_for_url(array("url" => $url)); array_push($spaceId, $space->space_id . ','); } foreach ($spaceId as $id) { print_r($id); } } catch (Exception $e) { print_r($e); } } else { print_r("Not auth"); } } public function getListDetails() { $userID = "5b06e0e3b500888f1d7b23c6"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { try { $spaces = Podio::get("/space/org/1339455/")->json_body(); $userArray = array(); foreach ($spaces as $space) { array_push($userArray, $space['space_id']); } } catch (Exception $e) { log::error($e); } } else { echo "No auth"; } echo "<pre>"; print_r($userArray); } public function getArray() { $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $spaces = Podio::get("/space/org/5264/")->json_body(); $array1 = array(); $var = 1; foreach ($spaces as $i => $space) { array_push($array1, $space['space_id']); } $groups = array_chunk($array1, (int)ceil(count($array1) / 8)); // print_r($groups); foreach ($groups as $k => $group) { print_r('$array' . $var . ' = array('); foreach ($group as $id) { if (end($group) == $id) { print_r(rtrim($id, ",")); print_r(');'); } else print_r($id . ','); } echo "<br>"; // echo count($group); // echo "<br>"; $var++; $array1 = array(); } exit; foreach ($spaces as $i => $space) { if ($space['space_id'] != 95998 && $space['space_id'] != 2159777) { if ($i != 0 && (($i + 1) % 29 == 0)) { array_push($array1, $space['space_id'] . ','); print_r('$array' . $var . ' = array('); foreach ($array1 as $id) { if (end($array1) == $id) { print_r(rtrim($id, ",")); print_r(');'); } else print_r($id); } $var++; echo "<br>"; $array1 = array(); } else { array_push($array1, $space['space_id'] . ','); } } } } } private static function valuesArray() { $array1 = array(3966864, 449933, 1238167, 351993, 2189763, 3490667, 4113658, 304168, 4028384, 1617630, 907435, 477478, 3290956, 2686332, 1714457, 4091916, 1803546, 1609655, 515055, 700458, 501888, 3941796, 1436486, 4559825, 571445, 823396, 1105087, 1321312, 3523727, 4379997, 4048775, 1598953, 1863427, 4566820, 4566770, 4160145, 3674999, 1401543); $array2 = array(348421, 1931223, 2287483, 2322660, 2565302, 2551704, 4514894, 1575760, 5207114, 774260, 1526183, 3672498, 1284297, 1925190, 4022831, 1882053, 3519570, 3796870, 634046, 633402, 881530, 5213840, 1195688, 3889638, 699963, 430808, 4598888, 1822755, 2034977, 5209346, 1690958, 1681033, 2548198, 3703742, 5087470, 1802249, 2578625, 3443100, 924205); $array3 = array(2058801, 2908300, 1790853, 2966094, 3639465, 2838476, 3515323, 337903, 2062126, 3815659, 390449, 4558117, 414114, 2372144, 303439, 335134, 1838497, 690332, 4411858, 2250537, 2008110, 4791056, 1397283, 3131940, 426544, 770616, 924958, 774582, 776767, 1652033, 1659623, 1659620, 1659622, 1659614, 1659619, 1793899, 1659618); $array4 = array(3716065, 2049379, 2458644, 609806, 3058937, 2258388, 4472885, 2881570, 5077283, 2414006, 1659613, 1659609, 1774844, 3142664, 3276751, 3268511, 3266537, 3266078, 3266376, 3266080, 3230409, 3142762, 4284398, 4374552, 4374539, 4374537, 4374535, 4337268, 4354213, 770603, 1344194, 3059041, 4284432, 335106, 2397456, 1200250, 2773981, 2287625, 3010511, 410366); $array5 = array(1523279, 3518275, 1084975, 941615, 364161, 1090120, 1011179, 1416201, 3501937, 2023431, 3733615, 1969692, 2760984, 335953, 2930381, 2445556, 2672828, 4970454, 4729076, 3952114, 342869, 1297896, 933125, 335459, 1511538, 3566407, 1297529, 1983609, 3495987, 3577030, 2337448, 1961463, 3692830, 3584641, 3309540, 2138037); $array6 = array(2422033, 5090894, 1665449, 392905, 3161924, 358816, 4321100, 2972839, 2886698, 4526932, 867995, 2397058, 532603, 3485852, 2723357, 1153808, 5251170, 726521, 4726481, 4896546, 734958, 2287791, 3440864, 4752699, 2057653, 4418818, 2574221, 4430687, 4430661, 4430719, 5014813, 4508803, 1229416, 4421978, 1131972, 4087967, 2315185, 3166672, 2054080, 3858039); $array7 = array(385374); $array8 = array(2343001); } public function getEnableAppComments() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $appId = 15051330; $appDetails = Podio::get("/app/$appId")->json_body(); if ($appDetails['config']['allow_comments']) { $newAppDetails['config'] = $appDetails['config']; $newAppDetails['config']['allow_comments'] = false; $resp = PodioApp::update($appId, $newAppDetails); print_r($resp); } } } public function getArchiveApp() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $appId = 15051330; PodioApp::deactivate($appId); } } public function getCreateStream() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $options = array('silent' => false, 'hook' => false); $status = array( "value" => "A copy of this workspace is now created under New organization. You can access the workspace using the link https://podio.com/podio-data-copy-src/workspace-1. All the employees needs to use the new workspace under new organization." ); $statusID = PodioStatus::create(4344480, $status, $options); } } public function getWorkspaceContacts() { $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { $spaceId = 4344480; $contacts = Podio::get("/contact/space/$spaceId/?contact_type=space&exclude_self=true&order=name")->json_body(); foreach ($contacts as $contact) { $podioFields = array(); foreach ($contact as $type => $values) { switch ($type) { case "mail": foreach ($values as $value) { $podioFields['email-address'][] = array("type" => "work", "value" => $value); } break; case "phone": foreach ($values as $value) { $podioFields['phone-number'][] = array("type" => "work", "value" => $value); } break; case "image": try { $fileID = PodioFile::copy($values->file_id); if (isset($fileID)) $podioFields["photo"][] = array("value" => $fileID->file_id); } catch (Exception $e) { log::error("No rights to add prev file"); } break; case "profile_id": $podioFields["profile-id"] = $values; break; case "skype": $podioFields["skype-id"] = $values; break; case "city": $podioFields["city"] = $values; break; case "name": $podioFields["name"] = $values; break; case "zip": $podioFields["post-code"] = $values; break; case "state": $podioFields["stateprovince"] = $values; break; case "country": $podioFields["country"] = $values; break; case "about": $podioFields["notes"] = $values; break; case "space_id": $podioFields["source-space-id"] = (int)$values; break; case "link": $podioFields["source-profile-link"] = $values . ''; break; case "url": foreach ($values as $value) { try { $fileID = PodioEmbed::create($attributes = array("url" => $value)); if (isset($fileID)) $podioFields["website"][] = array("embed" => $fileID->embed_id); } catch (Exception $e) { log::error("No rights to add prev file"); } } break; case "title": $text = ""; foreach ($values as $value) { $text .= $value . PHP_EOL; } $podioFields["job-title"] = $text; break; case "address": foreach ($values as $value) { $podioFields['address'][] = $value; } break; case "organization": $podioFields['organisation'][] = $values; break; } } $podioAttributes = array('fields' => $podioFields); $response = PodioItem::create(18357933, $podioAttributes, array('silent' => true)); } } } public function getListAllSpaces() { $userID = "5936292db50088c932edd124"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $spaces = Podio::get("/space/org/310355/")->json_body(); foreach ($spaces as $space) { if ($space['name'] !== 'Employee Network') { echo $space['space_id'] . ', '; } } } } public function getListLmiSpaces() { $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $spaces = Podio::get("/space/org/1249923/")->json_body(); foreach ($spaces as $space) { $spaceId = $space['space_id']; // $details = Podio::get("/space/$spaceId")->json_body(); if (strpos($space['url'], 'https://podio.com/logmein/') !== false) { try { Podio::delete("/space/$spaceId"); } catch (Exception $e) { echo $space['url'] . " Not able to be deleted <br>"; } } } } } public function getDeleteLmiApps($appId = array()) { $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { foreach ($appId as $app) { try { Podio::delete("/app/$app"); } catch (Exception $e) { echo $app . " Not able to be deleted <br>"; } } } } public function getEnableApp() { echo "<pre>"; $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $app = Podio::get("/app/18388041")->json_body(); $config = $app['config']; $config['approved'] = true; $config['allow_create'] = true; $config['silent_creates'] = false; $settings = array(); $settings['config'] = $config; try { PodioApp::update(18388041, $settings); } catch (Exception $e) { print_r($e); exit; } } } public function getDeleteComments() { $userID = "58d4acccb500886e28144551"; $authRepo = new AuthRepository(); $appId = array(598713598, 598713671, 598713696, 598713716, 598713738, 598713760, 598713787, 598713834); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { // foreach ($appId as $item) { $item = 598713598; try { $options = array('silent' => true, 'hook' => false); $attributes = array("reference" => "item:" . $item, "created_via" => 2993); $commentCollection = PodioTask::get_all($attributes, $options); // $commentCollection = Podio::get("/task/item/$item/")->json_body(); $count = count($commentCollection); foreach ($commentCollection as $comment) { PodioTask::delete($comment->task_id); echo "Deleting " . $comment->task_id . "<br>"; echo "<br>"; } } catch (Exception $e) { // echo $item . " Not able to be deleted <br>"; print_r($e); exit; } echo "Tasks deleted for " . $item . "<br>"; } // } } public function getAddOrg() { $userID = "5913f874b5008851274367cf"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { try { PodioSpace::create($attributes = array( "name" => "Test Space via API", "org_id" => 1278855, "privacy" => "open", "post_on_new_app" => false, "post_on_new_member" => false )); } catch (Exception $e) { print_r($e); exit; } } } public function getAddMember() { $userID = "5937a982b500880656edd124"; $authRepo = new AuthRepository(); echo "<pre>"; if ($this->authenticateHollow()) { try { // $user = PodioUser::get(); // print_r($user); // exit; $resp = PodioSpaceMember::add(5286913, $attributes = array( "role" => "admin", "message" => "You have been invited via API", // "users" => array(4124483,1004055), "mails" => array("ssp@phases.dk"), )); print_r($resp); } catch (Exception $e) { print_r($e); exit; } } } public function getAddApp() { $userID = "5937a982b500880656edd124"; $authRepo = new AuthRepository(); echo "<pre>"; if ($this->authenticateHollow()) { try { $app = Podio::get("/app/15016228")->json_body(); $newApp = array(); $newApp['space_id'] = 4334033; $newApp['config'] = $app['config']; $newApp['config']['name'] = "Test App via API"; $newApp['fields'] = $app['fields']; PodioApp::create($newApp); } catch (Exception $e) { print_r($e); exit; } } else { echo "No auth"; } } private function authenticateHollow() { $userID = "5937a982b500880656edd124"; $authRepo = new AuthRepository(); echo "<pre>"; if ($this->authenticateHollow()) { try { $app = Podio::get("/app/15016228")->json_body(); $newApp = array(); $newApp['space_id'] = 4334033; $newApp['config'] = $app['config']; $newApp['config']['name'] = "Test App via API"; $newApp['fields'] = $app['fields']; PodioApp::create($newApp); } catch (Exception $e) { print_r($e); exit; } } else { echo "No auth"; } } public function getToken() { $userObj = new User(); $user = $userObj->findOne(array('podioUserID' => 6163864)); if ($user) { echo Crypt::decrypt($user['podioAuth']['access_token']) . "<br>"; echo Crypt::decrypt($user['podioAuth']['refresh_token']); } } public function getItemDetails() { echo '<pre>'; try { $authRepo = new AuthRepository(); if ($authRepo->authenticateUser('5fdbaaf5edd8c459f763cd92')) { $limit = 100; $offset = 0; $totalCount = 0; do { $attributes = [ 'limit' => $limit, 'offset' => $offset ]; $itemComments = PodioComment::get_for('item', 1783681567, $attributes); $count = count($itemComments); $totalCount += $count; $offset += $limit; Log::info('TotalComments----> ' . $totalCount); } while ($limit == $count); echo $totalCount; } } catch (Exception $e) { print_r($e); } } public function getSharfile() { try { $uri = "https://phases781.sharefile.com/oauth/token"; echo "POST " . $uri . "\n"; $body_data = array( "grant_type" => "password", "client_id" => "KkYcGTCmPLrg2LUNsvCxVJwo2MjMmtJM", "client_secret" => "ou0eTVB56g45dl95fI1jvRtKJJwE3bVksMNOP1xrIgJizaa6", "username" => "nvj@phases.dk", "password" => "vu2jlxVA#" ); $data = http_build_query($body_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded')); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response echo $http_code . "\n"; // output http status code curl_close($ch); $token = NULL; if ($http_code == 200) { $token = json_decode($curl_response); } // $uri = "https://phases781/sf/v3/Users"; // echo "POST " . $uri . "\n"; // // $client = array("Email" => "nivin.v.joseph+1@phases.dk", "FirstName" => "Phases", "LastName" => "Test", "Company" => "Phases", // "Password" => "test123PH#", // "Preferences" => array("CanResetPassword" => false, "CanViewMySettings" => false)); //// "IsAdministrator" => false, //// "CanCreateFolders" => false, //// "CanUseFileBox" => true, //// "CanManageUsers" => false, //// "Roles" => [ //// "CanChangePassword", "CanManageMySettings", //// "CanUseFileBox", "CanManageUsers", "CanCreateFolders", "CanUseDropBox", "CanSelectFolderZone", //// "AdminAccountPolicies", "AdminBilling", "AdminBranding", "AdminChangePlan", "AdminFileBoxAccess", //// "AdminManageEmployees", "AdminRemoteUploadForms", "AdminReporting", "AdminSharedDistGroups", //// "AdminSharedAddressBook", "AdminViewReceipts", "AdminDelegate", "AdminManageFolderTemplates", //// "AdminEmailMessages", "AdminSSO", "AdminSuperGroup", "AdminZones", "AdminCreateSharedGroups", "AdminConnectors" //// ]); // $data = json_encode($client); // // $headers = array("Authorization: Bearer ".$token->access_token); // $headers[] = "Content-Type: application/json"; // // $ch = curl_init(); // curl_setopt($ch, CURLOPT_URL, $uri); // curl_setopt($ch, CURLOPT_TIMEOUT, 30); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // curl_setopt($ch, CURLOPT_POST, TRUE); // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // // $curl_response = curl_exec($ch); // dd($curl_response); // // $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // $curl_error_number = curl_errno($ch); // $curl_error = curl_error($ch); // // //echo $curl_response."\n"; // output entire response // echo "http_code = " . $http_code . "\n"; // output http status code // // curl_close($ch); // // if ($http_code == 200) { // $client = json_decode($curl_response); // print_r($client); // print entire new item object // echo "Created Client: " . $client->Id . "\n"; // } $uri = "https://phases781.sharefile.com/sf/v3/Users/AccountUser"; echo "POST " . $uri . "\n"; $client = array( "Email" => "nvj+3@phases.dk", "FirstName" => "Test", "LastName" => "Phases", "Company" => "Phases", "Password" => "password#Phases12", "notify" => true, "Preferences" => array("CanResetPassword" => false, "CanViewMySettings" => false) ); $data = json_encode($client); $headers = array("Authorization: Bearer " . $token->access_token); $headers[] = "Content-Type: application/json"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response echo "http_code = " . $http_code . "\n"; // output http status code curl_close($ch); if ($http_code == 200) { $client = json_decode($curl_response); print_r($client); // print entire new item object echo "Created Client: " . $client->Id . "\n"; } $uri = "https://phases781.sharefile.com/sf/v3/Users(" . $client->Id . ")/WelcomeNotification"; $client = array("CustomMessage" => "Welcome Email"); $data = json_encode($client); $headers = array("Authorization: Bearer " . $token->access_token); $headers[] = "Content-Type: application/json"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response echo "http_code = " . $http_code . "\n"; // output http status code } catch (Exception $e) { dd($e); exit; } } /*nivin fnctn*/ public function shareFileAuth() { echo "<pre>"; $uri = "https://ascentusone.sharefile.com/oauth/token"; $body_data = array( "grant_type" => "password", "client_id" => "21R0WJBkEJHyVf33xVH73KIhoo7skDLW", "client_secret" => "9PbF1xqFDLWjenYVAezgbbfF2GcQ0tnrKo8Ew4sdjYjuEe1z", "username" => "podio@ascentus1.com", "password" => "jjyh insc o5vt mqts" ); $data = http_build_query($body_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded')); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); curl_close($ch); $token = NULL; if ($http_code == 200) { $token = json_decode($curl_response); return $token; } } public function postShareConditionHook() { try { echo "<pre>"; $input = Input::all(); log::info($input); $file_id = $input['Event']['Resource']["Id"] . ""; $folderID = "foa14ad6-fc34-4db5-968c-1482953ff8d1"; //Test UW Conditions Folder log::info($file_id); $fileDetails = $this->getItem($file_id); log::info(print_r($fileDetails, true)); $file_id = $fileDetails->Id; $fileID = $this->getDuplicateFile($file_id, $folderID); $fileName = $fileDetails->Name; $loanNumber = filter_var($fileName, FILTER_SANITIZE_NUMBER_INT); $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $loanAppItems = PodioSearchResult::app(25688163, array( "query" => $loanNumber, "limit" => 1, "ref_type" => "item" )); if ($loanAppItems) { foreach ($loanAppItems as $loanAppItem) { $loanItemID = $loanAppItem->id; } } } $proceed = true; $itemDetails = Podio::get("/item/" . $loanItemID, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "conditions-after-ctc": foreach ($appItemField['values'] as $value) { $proceed = false; } break; } } $token = $this->shareFileAuth(); $fileLink = $this->getPreviewLink($token, $fileID); $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFileds["uw-conditions-folder"] = array("embed" => $fileID->embed_id); if ($proceed) { $podioFileds['status'] = array(7); //Status Conditions submission $comment['value'] = "Conditions are subitted in both clients and UWs Condition folder"; $response = PodioComment::create("item", $loanItemID, $comment, array('silent' => true, 'hook' => false)); } else { $podioFileds['status'] = array(8); } $podioAttributes = array('fields' => $podioFileds); $response = PodioItem::update($loanItemID, $podioAttributes, array('silent' => true)); //Email notification is sent to underwriter and pipeline analyst return $response; } catch (Exception $e) { log::error($e); } } public function postShareHook() { try { echo "<pre>"; $input = Input::all(); log::info($input); $file_id = $input['Event']['Resource']["Id"]; $fileDetails = $this->getItem($file_id); $fileName = $fileDetails->Name; $loanFolderId = $fileDetails->Parent->Id; $loanFolderDetails = $this->getItem($loanFolderId); $loanFolderName = $loanFolderDetails->Name; if (strpos($loanFolderName, 'PURCHASE') !== false) { $loanType = array(4); } else { $loanType = array(1); } $clientId = $loanFolderDetails->Parent->Id; $clientDetails = $this->getItem($clientId); $clientName = $clientDetails->Name; log::info($clientName); $fileCreator = $fileDetails->CreatorFirstName . " " . $fileDetails->CreatorLastName; log::info($fileCreator); $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $clientAppItems = PodioSearchResult::app(25682712, array( "query" => $clientName, "limit" => 1, "ref_type" => "item" )); if ($clientAppItems) { foreach ($clientAppItems as $clientAppItem) { $clientItemID = $clientAppItem->id; } } $contactAppItems = PodioSearchResult::app(25683953, array( "query" => $fileCreator, "limit" => 1, "ref_type" => "item" )); if ($contactAppItems) { foreach ($contactAppItems as $contactAppItem) { $contactItemID = $contactAppItem->id; } } else { $contactPodioDetails = array("name" => $fileCreator); $contactPodioAttributes = array('fields' => $contactPodioDetails); $response = PodioItem::create(25683953, $contactPodioAttributes, array('silent' => true)); $contactItemID = $response->item_id; } $fileName = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileName); $wordlist = array("Underwriting", "file", "Overlay", "Guideline", "Conventional", "Agency", "Guidelines", "UW", "pkg", "submission"); foreach ($wordlist as &$word) { $word = '/\b' . preg_quote($word, '/') . '\b/'; } $fileName = preg_replace($wordlist, '', $fileName); if (strpos($fileName, '_') !== false) { $fileName = str_replace("_", " ", $fileName); } // $loanNumber = filter_var($fileName, FILTER_SANITIZE_NUMBER_INT); $guideLineFolder = "fo5b86fc-25b5-440c-8370-5ee3b76f297f"; //Fetch from Podio client item $fileData = pathinfo($fileName); $extension = isset($fileData["extension"]) ? $fileData["extension"] : ""; $fileName = str_replace("." . $extension, "", $fileName); list( $loanNumber, $clientName, $borrowerName, $investorName, $investorId ) = $this->extractFileNameComponent($fileName, $guideLineFolder); Log::info($loanNumber); Log::info($borrowerName); Log::info($investorName); Log::info($investorId); // if ($fileName == trim($fileName) && strpos($fileName, ' ') !== false) { //Checkif file name has spaces // // $borrowerNames = explode(' ', trim($fileName)); // // $borrowerName = $borrowerNames[0]; // $borrowerName = str_replace($loanNumber, "", $fileName); // $borrowerName = str_replace(" ", "", $borrowerName); // } else { // $borrowerName = str_replace($loanNumber, "", $fileName); // } $token = $this->shareFileAuth(); $fileLink = $this->getPreviewLink($token, $file_id); $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFields = array( "client" => array($clientItemID), "processor" => array($contactItemID), "loan-number" => $loanNumber, "borrower-last-name" => $borrowerName, "loan-type" => $loanType, "document-link" => array("embed" => $fileID->embed_id), "loan-file-id" => $file_id ); log::info($podioFields); $podioAttributes = array('fields' => $podioFields); $response = PodioItem::create(25688163, $podioAttributes, array('silent' => true)); if ($investorName == "") { $comment['value'] = "System has identified that there is additional text in the loan file name but could not locate a Guidelines/Overlays file for the loan file. Please check and verify if the last name has been identified correctly and if needed manually share the overlays file with the underwriter"; PodioComment::create("item", $response->item_id, $comment, array('silent' => true, 'hook' => false)); } else { $token = $this->shareFileAuth(); $fileLink = $this->getPreviewLink($token, $investorId); Log::info($fileLink); $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFileds["fields"]["guidelines-and-overlays"] = array("embed" => $fileID->embed_id); PodioItem::update($response->item_id, $podioFileds, array("Silent" => true)); /** *TODO get the sharefile link */ // $childrens = $this->getItemChildren($guideLineFolder); // $sharableLink = $this->getFolderOrFileSharableLink($investorId); } } } catch (Exception $e) { log::error($e); exit; } } /** * Extract file name componentes * * File name components * 1. Loan number * 2. client name * 3. borrower last name * 4. investor name * * @param string $fileName * @param string $guideLineFolder * @return array */ private function extractFileNameComponent($fileName, $guideLineFolder, $loanNumer = false) { try { $loanNumber = $loanNumer; $clientName = ""; $borrowerName = ""; $investorName = ""; $investorId = 0; // $loanNumber = filter_var($fileName, FILTER_SANITIZE_NUMBER_INT); /** * Removing loan-number from the file name */ $fileName = trim(str_replace($loanNumber, "", $fileName)); /** * @var array $allGuideLineFoldersAndFiles all folders, files from the guideline */ $allGuideLineFoldersAndFiles = $this->allGuildeLineFoldersAndFiles($guideLineFolder); if ($allGuideLineFoldersAndFiles === false) { /** * TODO do a podio comment, which state that there's no data is found from the sharefiles */ // throw new Exception("No guideline folders, and files are found"); } $investorName = ""; foreach ($allGuideLineFoldersAndFiles as $id => $name) { // if (str_contains($fileName, $name)) { $investorName = $name; $investorId = $id; // } } /** * NOTE removing the investor-name from the file name */ $fileName = trim(str_replace($investorName, "", $fileName)); $borrowerName = $fileName; return [ $loanNumber, $clientName, $borrowerName, $investorName, $investorId ]; } catch (Exception $e) { Log::error($e->getMessage()); Log::error($e); return [false, false, false, false]; } } private function allGuildeLineFoldersAndFiles($folderId) { try { $foldersAndFileNames = []; /** * @var stdClass $subFoldersAndFiles sub folders/files from the guide line folder */ $subFoldersAndFiles = $this->getItemChildren($folderId); if (property_exists($subFoldersAndFiles, "Children")) { $subFoldersAndFiles = $subFoldersAndFiles->Children; foreach ($subFoldersAndFiles as $data) { $fileName = $data->Name; $pathInfo = pathinfo($fileName); $extension = isset($pathInfo["extension"]) ? $pathInfo["extension"] : ""; $fileName = str_replace("." . $extension, "", $fileName); $foldersAndFileNames[$data->Id] = $fileName; } } return $foldersAndFileNames; } catch (Exception $e) { Log::error($e->getMessage()); Log::error($e); return false; } } public function postInputHook() { $input = Input::all(); $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { switch ($input['type']) { case 'item.create': try { $itemId = $input['item_id']; $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "email-address": foreach ($appItemField['values'] as $value) { $contactEmail = $value['value']; } break; } } if (!empty($contactEmail)) { $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Users?emailaddress=$contactEmail"); if (!empty($response->Emails)) { print_r($response->FullName); //suceess } //return $response; } } catch (Exception $e) { Log::error($e); } break; } } } public function postHook($option = null) { $input = Input::all(); log::info($input); $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { if (isset($option) && !empty($option)) { switch ($input['type']) { case "hook.verify": try { if ($input['code'] && $input['hook_id']) { PodioHook::validate($input['hook_id'], array('code' => $input['code'])); } } catch (PodioError $e) { Log::error($e); } break; case 'item.create': $itemId = $input['item_id']; $token = $this->shareFileAuth(); $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "title": foreach ($appItemField['values'] as $value) { $clientName = $value['value']; } break; } } if (preg_match('/[a-jA-J]/', $clientName[0])) { $TargetFolderID = "fo58c43a-cc93-463c-8e6b-a18671c47045"; // A-J fod34669-5a1b-4530-a307-4f744683f4a0 } elseif (preg_match('/[k-rK-R]/', $clientName[0])) { $TargetFolderID = "fo645753-8f87-4c32-af53-4e90ff9b091d"; // K-R fo9918ef-a29e-44d4-b68a-1f1c0203f97a } elseif (preg_match('/[s-zS-Z]/', $clientName[0])) { $TargetFolderID = "fo07b812-8216-4aac-8950-2e31b38b7f0d"; // S-Z fo5cedd2-a815-44e4-98c9-cc28114792d6 } print_r($TargetFolderID); // $folder = array("Name" => $clientName, "Description" => ""); // $resposne = $this->SFDataPost($token, "Items(" . $TargetFolderID . ")/Folder?overwrite=false&passthrough=false", $folder); // $folderID = $resposne->Id; // $createdClientFolder = $this->getDuplicateFile("fo147ade-322c-4698-8f4c-e0e8b0b21db9", $TargetFolderID); // $data = array("FileName" => $clientName, "Name" => $clientName); // $updateFolder = $this->SFDataPatch($token, "Items(" . $createdClientFolder . ")?overwrite=false", $data); //// print_r($updateFolder); // $fileLink = $this->getPreviewLink($token, $createdClientFolder); // $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); // $podioFileds["link-to-sharefile-master-folder"] = array("embed" => $fileID->embed_id); // $podioAttributes = array('fields' => $podioFileds); // PodioItem::update($itemId, $podioAttributes, array("Silent" => true)); break; } } else { switch ($input['type']) { case "hook.verify": try { if ($input['code'] && $input['hook_id']) { PodioHook::validate($input['hook_id'], array('code' => $input['code'])); } } catch (PodioError $e) { Log::error($e); } break; case 'item.update': $itemId = $input['item_id']; Log::info('Here entered'); $itemRev = PodioItemRevision::get_for($itemId); if (isset($itemRev) && !empty($itemRev)) { Log::info('Here entered 123'); $lastRev = end($itemRev); $revId = $lastRev->revision; $revId = 2; $revMade = PodioItemDiff::get_for($itemId, 2 - 1, 2); print_r($revMade); if ($revMade[0]->field_id == "218985513") { Log::info('Here entered 123558'); log::info("Here"); $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "loan-file-id": foreach ($appItemField['values'] as $value) { $fileID = $value['value']; } break; case "ldd-folder-name": foreach ($appItemField['values'] as $value) { $LDDFolderName = $value['value']; } break; } } $this->getCreateFolderLdd($fileID, $itemId, $LDDFolderName); } elseif ($revMade[0]->field_id == "218985514" && ($revMade[0]->to[0]['value']['id'] == 3 || $revMade[0]->to[0]['value']['id'] == 9)) { //Initial Review Completed //Notify pipeline analyst in Podio $LDDFileName = ""; $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "loan-ldd-file-id": foreach ($appItemField['values'] as $value) { $LDDFileID = $value['value']; } break; case "h-uw-ldd-folder": foreach ($appItemField['values'] as $value) { $LDDFolderID = $value['value']; } break; case "assigned-underwriter": foreach ($appItemField['values'] as $value) { $UWItem = $value['value']['item_id']; } break; } } $uwDetails = Podio::get("/item/" . $UWItem, array())->json_body(); // if Check if underwriter has "Direct Access" role permission foreach ($uwDetails['fields'] as $uwItemField) { switch ($uwItemField['external_id']) { case "role-permissions": foreach ($uwItemField['values'] as $value) { $permission = $value['value']['id']; } break; } } if ($permission == 1 || $permission == 2 || $permission == 5) { $comment['value'] = "Underwriter does not have enough permission to move the LDD file to client folder."; PodioComment::create("item", $itemId, $comment, array('silent' => true, 'hook' => false)); // Alert Supervisor } else if ($permission == 3 || $permission == 4 || $permission == 6) { $folderID = "fobad951-3358-49d1-9528-05eebd370aed"; //Test Client LDD Folder $UWLDDFiles = $this->getItemChildren($LDDFolderID); if (property_exists($UWLDDFiles, "Children")) { foreach ($UWLDDFiles->Children as $child) { if (strpos($child->Name, "LDD") !== false && strpos($child->Name, ".pdf") == false) { $date = strtotime($child->CreationDate); if (isset($preVdate)) { if ($date > $preVdate) { $LDDFileID = $child->Id; $LDDFileName = $child->Name; } } else { $LDDFileID = $child->Id; } $preVdate = $date; } } } $uploadFileName = str_replace(" ", "_", $LDDFileName); $url = "https://hubspot-bigquery.bitkit.dk/sharefile/upload/{$LDDFileID}/{$folderID}/{$uploadFileName}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); Log::info("upload response {$result}"); if ($result > 0) { $comment['value'] = "LDD file is moved to clients LDD Folder"; PodioComment::create("item", $itemId, $comment, array('silent' => true, 'hook' => false)); } /* * NOTE previous file upload ( copy ) logic commeted below */ // $this->getDuplicateFile($LDDFileID, $folderID); $podioFileds = array(); $podioFileds['status'] = array(5); //Status "LDD submitted" $podioAttributes = array('fields' => $podioFileds); PodioItem::update($itemId, $podioAttributes, array("Silent" => true)); } } elseif ($revMade[0]->field_id == "218985514" && ($revMade[0]->to[0]['value']['id'] == 5)) { //Initial Review Completed //Notify pipeline analyst in Podio $LDDFileName = ""; $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "loan-ldd-file-id": foreach ($appItemField['values'] as $value) { $LDDFileID = $value['value']; } break; case "h-uw-ldd-folder": foreach ($appItemField['values'] as $value) { $LDDFolderID = $value['value']; } break; case "assigned-underwriter": foreach ($appItemField['values'] as $value) { $UWItem = $value['value']['item_id']; } break; } } $folderID = "fobad951-3358-49d1-9528-05eebd370aed"; //Test Client LDD Folder $UWLDDFiles = $this->getItemChildren($LDDFolderID); $copy = true; if (property_exists($UWLDDFiles, "Children")) { foreach ($UWLDDFiles->Children as $child) { if (strpos($child->Name, ".pdf") == false || strpos($child->Name, "LDD") !== false) { $date = strtotime($child->CreationDate); if (isset($preVdate)) { if ($date > $preVdate) { $LDDFileID = $child->Id; $LDDFileName = $child->Name; if (strpos($child->Name, ".pdf") == false) { $copy = false; } else { $copy = true; } } } else { $LDDFileID = $child->Id; if (strpos($child->Name, ".pdf") == false) { $copy = false; } else { $copy = true; } } $preVdate = $date; } } } if (!$copy) { $uploadFileName = str_replace(" ", "_", $LDDFileName); $url = "https://hubspot-bigquery.bitkit.dk/sharefile/upload/{$LDDFileID}/{$folderID}/{$uploadFileName}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); } else { $this->getDuplicateFile($LDDFileID, $folderID); $result = 1; } Log::info("upload response {$result}"); if ($result > 0) { $comment['value'] = "LDD file is moved to clients LDD Folder"; PodioComment::create("item", $itemId, $comment, array('silent' => true, 'hook' => false)); } /* * NOTE previous file upload ( copy ) logic commeted below */ // $this->getDuplicateFile($LDDFileID, $folderID); // $podioFileds = array(); // $podioFileds['status'] = array(5); //Status "LDD submitted" // $podioAttributes = array('fields' => $podioFileds); // PodioItem::update($itemId, $podioAttributes, array("Silent" => true)); } elseif ($revMade[0]->field_id == "218985514" && $revMade[0]->to[0]['value']['id'] == 4) { $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "loan-ldd-file-id": foreach ($appItemField['values'] as $value) { $LDDFileID = $value['value']; } break; case "assigned-underwriter": foreach ($appItemField['values'] as $value) { $UWItem = $value['value']['item_id']; } break; case "h-uw-ldd-folder": foreach ($appItemField['values'] as $value) { $LDDFolderID = $value['value']; } break; } } $uwDetails = Podio::get("/item/" . $UWItem, array())->json_body(); // if Check if underwriter has "Direct Access" role permission foreach ($uwDetails['fields'] as $uwItemField) { switch ($uwItemField['external_id']) { case "role-permissions": foreach ($uwItemField['values'] as $value) { $permission = $value['value']['id']; } break; } } if ($permission == 3 || $permission == 4 || $permission == 6) { $folderID = "fo7562a1-6cfb-46cf-944c-2a2a18c70ba0"; //Test Client CTC LDD $UWLDDFiles = $this->getItemChildren($LDDFolderID); if (property_exists($UWLDDFiles, "Children")) { foreach ($UWLDDFiles->Children as $child) { if (strpos($child->Name, "LDD") !== false && strpos($child->Name, ".pdf") == false) { $date = strtotime($child->CreationDate); if (isset($preVdate)) { if ($date > $preVdate) { $LDDFileID = $child->Id; $LDDFileName = $child->Name; } } else { $LDDFileID = $child->Id; } $preVdate = $date; } } } $uploadFileName = str_replace(" ", "_", $LDDFileName); $url = "https://hubspot-bigquery.bitkit.dk/sharefile/upload/{$LDDFileID}/{$folderID}/{$uploadFileName}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); Log::info("upload response {$result}"); if ($result > 0) { $comment['value'] = "LDD file is moved to clients LDD Folder"; PodioComment::create("item", $itemId, $comment, array('silent' => true, 'hook' => false)); } $podioFileds = array(); $podioFileds['status'] = array(6); //Status "CTC LDD submitted" $podioAttributes = array('fields' => $podioFileds); PodioItem::update($itemId, $podioAttributes, array("Silent" => true)); } // else GF TO Notify QC analyst associated with UW } elseif ($revMade[0]->field_id == "218985514" && $revMade[0]->to[0]['value']['id'] == 6) { $LDDFolderID = 0; // if NOT Check if underwriter has "Direct Access" role permission $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "loan-ldd-file-id": foreach ($appItemField['values'] as $value) { $LDDFileID = $value['value']; } break; case "h-uw-ldd-folder": foreach ($appItemField['values'] as $value) { $LDDFolderID = $value['value']; } break; } } $folderID = "fo7562a1-6cfb-46cf-944c-2a2a18c70ba0"; //Test Client LDD Folder $UWLDDFiles = $this->getItemChildren($LDDFolderID); $copy = true; if (property_exists($UWLDDFiles, "Children")) { foreach ($UWLDDFiles->Children as $child) { if (strpos($child->Name, ".pdf") == false || strpos($child->Name, "LDD") !== false) { $date = strtotime($child->CreationDate); if (isset($preVdate)) { if ($date > $preVdate) { $LDDFileID = $child->Id; $LDDFileName = $child->Name; if (strpos($child->Name, ".pdf") == false) { $copy = false; } else { $copy = true; } } } else { $LDDFileID = $child->Id; if (strpos($child->Name, ".pdf") == false) { $copy = false; } else { $copy = true; } } $preVdate = $date; } } } if (!$copy) { $uploadFileName = str_replace(" ", "_", $LDDFileName); $url = "https://hubspot-bigquery.bitkit.dk/sharefile/upload/{$LDDFileID}/{$folderID}/{$uploadFileName}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); } else { $this->getDuplicateFile($LDDFileID, $folderID); $result = 1; } $comment['value'] = "Completed LDD file is moved to clients CTC LDD Folder"; PodioComment::create("item", $itemId, $comment, array('silent' => true, 'hook' => false)); } } break; case 'item.create': $itemId = $input['item_id']; $token = $this->shareFileAuth(); $itemId = $input['item_id']; $itemDetails = Podio::get("/item/" . $itemId, array())->json_body(); foreach ($itemDetails['fields'] as $appItemField) { switch ($appItemField['external_id']) { case "title": foreach ($appItemField['values'] as $value) { $clientName = $value['value']; } break; } } $TargetFolderID = "fo58c43a-cc93-463c-8e6b-a18671c47045"; // $folder = array("Name" => $clientName, "Description" => ""); // $resposne = $this->SFDataPost($token, "Items(" . $TargetFolderID . ")/Folder?overwrite=false&passthrough=false", $folder); // $folderID = $resposne->Id; $createdClientFolder = $this->getDuplicateFile("foaa0bf6-bd44-4f60-909b-192031c9d754", $TargetFolderID); $data = array("FileName" => $clientName, "Name" => $clientName); $updateFolder = $this->SFDataPatch($token, "Items(" . $createdClientFolder . ")?overwrite=false", $data); // print_r($updateFolder); $fileLink = $this->getPreviewLink($token, $createdClientFolder); $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFileds["link-to-sharefile-master-folder"] = array("embed" => $fileID->embed_id); $podioAttributes = array('fields' => $podioFileds); PodioItem::update($itemId, $podioAttributes, array("Silent" => true)); break; } } } } /** * Download file from the given item id * * @param string $itemId share-file item id * @return string */ private function downloadFileFromItem($itemId, $fileName) { try { $fileName = str_replace(" ", "_", $fileName); $downloadContent = $this->getItemDownloadContent($itemId); if (!$downloadContent) { throw new Exception("No download content is found, item_id:{$itemId}"); } $downloadUrl = isset($downloadContent->DownloadUrl) ? $downloadContent->DownloadUrl : ""; if (!$downloadUrl) { throw new Exception("No download url is found, item_id:{$itemId}"); } $storagePath = storage_path("app/public/$fileName"); $download = $this->downloadFile($downloadUrl, $storagePath); if (!$download) { throw new Exception("File download is failed, url:{$downloadUrl}, item_id:{$itemId}"); } return $storagePath; } catch (Exception $e) { log::error($e->getMessage()); log::error($e); return ""; } } // public function duplicateFile($fileID, $TargetFolderID){ public function getDuplicateFile($fileID = "", $TargetFolderID = "") { try { $token = $this->shareFileAuth(); // $fileID = "fif20e5c-96fa-c401-5e42-2c937be9f6e2 "; // $TargetFolderID = "fob930c1-2e8d-459a-bf72-e5a115faa9e7"; log::info($fileID); log::info($TargetFolderID); $resposne = $this->SFDataPost($token, "Items(" . $fileID . ")/Copy?targetid=" . $TargetFolderID . "&overwrite=false"); // print_r($resposne); log::info(print_r($resposne, true)); return $resposne->Id; } catch (Exception $e) { log::error($e); exit; } } public function getEditFile($fileID) { try { return "https://ascentusone.sharefile.com/document/edit/" . $fileID; } catch (Exception $e) { log::error($e); exit; } } public function getCreateFolderLdd($fileID = "", $podioItem = "", $LDDFolderName, $TargetFolderID = "") { try { log::info("Create LDD"); $token = $this->shareFileAuth(); $TargetFolderID = "fo124b33-a895-4d91-afd2-b9f06718f4c7"; $folder = array("Name" => $LDDFolderName, "Description" => ""); $resposne = $this->SFDataPost($token, "Items(" . $TargetFolderID . ")/Folder?overwrite=false&passthrough=false", $folder); $folderID = $resposne->Id; $fileLink = "https://ascentusone.sharefile.com/home/shared/" . $folderID; $fileIDs = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFileds = array(); $podioFileds["uw-ldd-folder"] = array("embed" => $fileIDs->embed_id); $LDDFile = $this->getDuplicateFile("fi60003a-7d24-92ad-9e75-8d5e82e64048", $folderID); //Test Client LDD File $podioFileds["loan-ldd-file-id"] = $LDDFile; $lddFileLink = $this->getEditFile($LDDFile); $podioFileds["uw-ldd-file-link"] = $lddFileLink; $podioFileds["h-uw-ldd-folder"] = $folderID; $this->getDuplicateFile("fi1a156a-df76-7191-b9b8-8d1ee8a1e62b", $folderID); //ATR Worksheet $this->getDuplicateFile("fic1b251-6f45-9f1a-c073-f71c99e8f89e", $folderID); //UAV Form $UWLDDFiles = $this->getItemChildren($folderID); if (property_exists($UWLDDFiles, "Children")) { foreach ($UWLDDFiles->Children as $child) { if (strpos($child->Name, "UAV") !== false) { $UAVId = $child->Id; } elseif (strpos($child->Name, "ATR") !== false) { $ATRId = $child->Id; } } } $UAVFileLink = $this->getEditFile($UAVId); $podioFileds["uw-uav-file-link"] = $UAVFileLink; $ATRFileLInk = $this->getEditFile($ATRId); $podioFileds["uw-atr-file-link"] = $ATRFileLInk; $fileID = $this->getDuplicateFile($fileID, "fofdfa1c-4f79-4d23-8308-06cc6b5a105d"); //New Loans Underwriter $fileLink = $this->getPreviewLink($token, $fileID); $fileID = PodioEmbed::create($attributes = array("url" => $fileLink)); $podioFileds["source-folder"] = array("embed" => $fileID->embed_id); $comment['value'] = "Folder with LDD template created for loan and shared with Underwriter."; PodioComment::create("item", $podioItem, $comment, array('silent' => true, 'hook' => false)); $podioAttributes = array('fields' => $podioFileds); PodioItem::update($podioItem, $podioAttributes, array("Silent" => true)); // print_r($resposne); } catch (Exception $e) { log::error($e); exit; } } public function getCreateShareFileHook() { $token = $this->shareFileAuth(); $data = array( "SubscriptionContext" => array("ResourceType" => "Folder", "ResourceId" => "fo87aba3-fab3-4414-bb59-81dba04a85c4"), "WebhookUrl" => "https://podiocopy.phases.dk/test/share-hook", "Events" => [ array( "ResourceType" => "File", "OperationName" => "Upload" ) ] ); $resposne = $this->SFDataPost($token, "WebhookSubscriptions", $data); print_r($resposne); } private function getItemDownloadContent($itmeId) { $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Items(" . $itmeId . ")/Download?includeallversions=false&includeDeleted=false&redirect=false"); return $response; } private function downloadFile($url, $local_path) { try { $token = $this->shareFileAuth(); $fp = fopen($local_path, 'w'); $headers = $this->get_authorization_header($token); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_VERBOSE, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_exec($ch); $curl_error_number = curl_errno($ch); if ($curl_error_number) { throw new Exception("The file download is failed, curl error number:{$curl_error_number}"); } $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code != 200) { throw new Exception("The file could'nt able to download, url:{$url}"); } curl_close($ch); fclose($fp); return true; } catch (Exception $e) { Log::error($e->getMessage()); Log::error($e); return false; } } public function getFavFolders() { $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Users(ea0d9dfa-5858-4da6-adab-7f063874a22d)/Favorites"); print_r($response); } // public function getPreviewLink($token = "", $item = "") // { // $token = $this->shareFileAuth(); //// $response = $this->SFDataGet($token, "Items(" . $item . ")/WebView"); // $response = $this->SFDataGet($token, "Items(" . $item . ")/WebView"); //// $response = $this->SFDataPost($token, "Shares(fofdfa1c-4f79-4d23-8308-06cc6b5a105d)/Alias?email=nivin.v.joseph@phases.dk"); // print_r($response); // exit; // return $response->Uri; // } public function getPreviewLink($token = "", $item = "") { try { $token = $this->shareFileAuth(); $filetype = substr($item, 0, 2); if ($filetype == 'fo') { $is_view_only = false; } else { $is_view_only = true; } // "Recipients" => [array("User" => array("Email" => "podio@ascentus1.com"))], $data = array( "ShareType" => "Send", "Title" => "UW LDD Folder Share", "Items" => [array("Id" => $item)], "MaxDownloads" => -1, "IsViewOnly" => $is_view_only, "UsesStreamIDs" => false ); $response = $this->SFDataPost($token, "Shares?notify=false", $data); if (isset($response->Uri)) return $response->Uri; else return null; } catch (Exception $e) { log::error($e); } } public function getUsers() { $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Users?emailaddress=podio@ascentus1.com"); print_r($response); } public function getItem($itmeId) { // $token = $this->shareFileAuth(); // $response = $this->SFDataGet($token, "Items(" . $itmeId . ")?includeDeleted=false"); // return $response; } public function getItemChildren($folderID = "fo5b86fc-25b5-440c-8370-5ee3b76f297f") { echo "<pre>"; $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Items(" . $folderID . ")?\$expand=Children&\$select=Id,Name,Children/Id,Children/Name,Children/CreationDate"); // if (property_exists($response, "Children")) { // foreach ($response->Children as $child) { // if (strpos($child->Name, ".pdf") !== false || strpos($child->Name, "LDD") !== false) { // echo $child->Name . "\n"; // echo $child->CreationDate . "\n"; // $date = strtotime($child->CreationDate); // if (isset($preVdate)) { // if ($date > $preVdate) { // $latestFile = $child->Id; // } // } else { // $latestFile = $child->Id; // } // $preVdate = $date; // } // } // } return $response; } /*sonia - fnctn Test function*/ public function getChildItem() { try { $favItemChildren = $this->getItemChildren(); if (!empty($favItemChildren->Children)) { foreach ($favItemChildren->Children as $child) { $itemDetails = $this->getItem($child->Id); $filetype = substr($child->Id, 0, 2); if ($filetype == 'fo') { $folderChildren = $this->getItemChildren($child->Id); foreach ($folderChildren->Children as $folderchild) { $filetype = substr($folderchild->Id, 0, 2); if ($filetype == 'fo') { } else { } } exit; } else { echo 'File'; echo '<br>'; } } } } catch (Exception $e) { dd($e); exit; } } /*sonia-fnctn Initial sync for clients*/ public function getClientInitialSync() { try { $folderId = 'fob380e2-0de6-495d-881a-a5429f29f8b2'; $favItemChildren = $this->getItemChildren($folderId); $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { foreach ($favItemChildren->Children as $itemChild) { $clientName = $itemChild->Name; if (strpos($clientName, '- Inactive Temporarily') !== false) { $clientName = str_replace("- Inactive Temporarily", "", $clientName); } elseif (strpos($clientName, '- inactive') !== false) { $clientName = str_replace("- inactive", "", $clientName); } elseif (strpos($clientName, '-inactive') !== false) { $clientName = str_replace("-inactive", "", $clientName); } elseif (strpos($clientName, '- Inactive') !== false) { $clientName = str_replace("- Inactive", "", $clientName); } elseif (strpos($clientName, '-Inactive') !== false) { $clientName = str_replace("-Inactive", "", $clientName); } elseif (strpos($clientName, 'inactive') !== false) { $clientName = str_replace("inactive", "", $clientName); } elseif (strpos($clientName, '-') !== false) { $clientName = str_replace("-", " ", $clientName); } $clientName = trim($clientName); $clientFolderId = $itemChild->Id; // $app_id = 25682712; $app_id = 25689843; //underwriter appid $this->checkFolderName($app_id, $clientName, $clientFolderId); } } } catch (Exception $e) { dd($e); exit; } } /*sonia - fntn helper - check foldername*/ public function checkFolderName($app_id, $clientName, $clientFolderId) { try { $getClientNames = PodioSearchResult::app($app_id, array( "query" => $clientName, "limit" => 1, "ref_type" => "item" )); if (!empty($getClientNames)) { foreach ($getClientNames as $getClientName) { $ClientItemID = $getClientName->id; $ClientItemtitle = $getClientName->title; if (strpos($ClientItemtitle, '-') !== false) { $ClientItemtitle = str_replace("-", " ", $ClientItemtitle); } $sh_titllelowercase = trim(strtolower($clientName)); $podio_titllelowercase = trim(strtolower($ClientItemtitle)); if (!empty($ClientItemID) && !empty($podio_titllelowercase)) { if ($sh_titllelowercase == $podio_titllelowercase) { if (!empty($ClientItemID)) { $attributes = array('fields' => array('h-sharefile-folder-id' => $clientFolderId)); // $sucess = PodioItem::update( $ClientItemID, $attributes, array("Silent" => true)); echo $podio_titllelowercase; echo "<br>"; } } else { echo $podio_titllelowercase; echo "<br>"; } } } } else { echo $clientName; echo "<br>"; } } catch (Exception $e) { dd($e); exit; } } /*sonia - fntcn helper - get update all appItems*/ public function getUpdateAllAppItems() { try { $app_id = 25689843; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $limit = 10; $offset = (int)$_GET['offset']; $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $AppItems = PodioItem::filter($app_id, $attributes, $options = array()); foreach ($AppItems as $appItem) { $share_file_folder_id = null; if ($appItem->item_id) { foreach ($appItem->fields as $field) { switch ($field->external_id) { case "h-sharefile-folder-id": $share_file_folder_id = $field->values; break; } if (!empty($share_file_folder_id)) { $getfolderChildren = $this->getItemChildren($share_file_folder_id)->Children; $child_condition_folder_id = null; $child_ldds_folder_id = null; $child_guidelines_folder_id = null; $child_new_loans_folder_id = null; $child_loan_refis = null; $child_purchase_folder_id = null; $child_ctcldd_folder_id = null; foreach ($getfolderChildren as $getFolderName) { if (strpos($getFolderName->Name, "Condition") !== false) { $child_condition_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; } elseif (strpos($getFolderName->Name, "LDD's") !== false) { $child_ldds_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; } elseif (strpos($getFolderName->Name, "Guideline") !== false) { $child_guidelines_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; } elseif (strpos($getFolderName->Name, "New Loan") !== false) { $child_new_loans_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; } // elseif ($getFolderName->Name == 'CTC LDD'){ // $child_ctcldd_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; // } // elseif (strpos($getFolderName->Name, "Refi") !== false){ // $child_loan_refis = !empty($getFolderName->Id) ? $getFolderName->Id : ''; // }elseif (strpos($getFolderName->Name, "Purchase") !== false){ // $child_purchase_folder_id = !empty($getFolderName->Id) ? $getFolderName->Id : ''; // } } $Podioattributes = array('fields' => array( 'h-guidelines-folder-id' => !empty($child_guidelines_folder_id) ? $child_guidelines_folder_id : null, 'h-conditions-folder-id' => !empty($child_condition_folder_id) ? $child_condition_folder_id : null, 'h-ldd-folder-id' => !empty($child_ldds_folder_id) ? $child_ldds_folder_id : null, 'h-new-loans-folder-id' => !empty($child_new_loans_folder_id) ? $child_new_loans_folder_id : null, // 'h-ctc-ldd-folder-id'=>!empty($child_ctcldd_folder_id) ? $child_ctcldd_folder_id : null, // 'h-new-loan-purchase-folder-id'=>!empty($child_purchase_folder_id) ? $child_purchase_folder_id : null, // 'h-new-loan-ref-folder-id'=>!empty($child_loan_refis) ? $child_loan_refis : null, )); // $result = PodioItem::update($appItem->item_id, $Podioattributes, array("Silent" => true)); // if($result){ // echo $appItem->title .' '.$appItem->item_id; // echo "<br>"; // } } } } } } } catch (Exception $e) { dd($e); exit; } } /*helper - get CLient details*/ public function getClientDetails($getclientId) { $resp = PodioItem::get($getclientId); return $resp; } /*sonia fntcn - appid and fieldid*/ public function getItemFieldValue() { try { $item_id = 1647000544; $field_id = 219678973; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $getFieldvalue = PodioItem::get_field_value($item_id, $field_id); if ($getFieldvalue) { if (count($getFieldvalue) == 1 && count($getFieldvalue) != 0) { $item_ref_id = $getFieldvalue[0]['value']['item_id']; } else { $item_ref_id = array(); foreach ($getFieldvalue as $value) { $item_ref_id[] = $value['value']['item_id']; } } return $item_ref_id; } } } catch (Exception $e) { dd($e); exit; } } /*sonia fntn - app reference*/ public function getItemAppReference() { try { $item_id = 1629818699; $app_id = 25682712; //$item_id = 1640860884; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $references = PodioItem::get_references($item_id); if (!empty($references)) { foreach ($references as $reference) { $ref_app_id = $reference['app']['app_id']; if ($ref_app_id == $app_id) { if (!empty($reference['items'])) { if (count($reference['items']) == 1 && count($reference['items']) != 0) { $item_ids = $reference['items'][0]['item_id']; } else { $item_ids = array(); foreach ($reference['items'] as $item) { $item_ids[] = $item['item_id']; } } } } } } return $item_ids; } } catch (Exception $e) { dd($e); exit; } } /*soniafncn - webshook sunsbritin*/ public function getWebhookSubscribs() { $Id = 'fo195daa-0a5d-4aba-a9a6-05b7fe20a97a'; $type = "WebhookSubscriptions"; $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, $type); print_r($response); } /*sonia fnctn - search functon*/ // public function getShareFileSearch($query, $client_conditions_folder_id, $client_guidelines_folder, $new_loan_ref, $new_loan_purchase, $client_item_id, $ldd_file_folder_id, $ctc_file_folder_id, $status) public function getShareFileSearch() { try { $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $folder = Input::get('folder'); $getFolderChildren = $this->getItemChildren($folder)->Children; $childCount = 0; if (count($getFolderChildren) > 0) { Log::info("Processing started of client"); $client_conditions_folder_id = Input::get('conditionsID'); $client_guidelines_folder = Input::get('guidelinesID'); $new_loan_ref = Input::get('newLoanRefID'); $new_loan_purchase = Input::get('newLoanPurchaseID'); $client_item_id = (int)Input::get('clientItemID'); $ldd_file_folder_id = Input::get('LDDID'); $ctc_file_folder_id = Input::get('CTCLDDID'); $status = (int)Input::get('status'); foreach ($getFolderChildren as $ChildItem) { $childCount++; $string = $ChildItem->Name; if (preg_match_all("/(\d{3,})/", $string, $match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 2022, 2018))) { $loanId = $number; } } } else { if (!($this->nBetween($match[0], 2022, 2018))) { $loanId = $match[0]; } } } if (!empty($loanId)) { $hookParams = [ 'count' => $childCount, 'loan' => $loanId, 'conditionsID' => $client_conditions_folder_id, 'guidelinesID' => $client_guidelines_folder, 'newLoanRefID' => $new_loan_ref, 'newLoanPurchaseID' => $new_loan_purchase, 'clientItemID' => $client_item_id, 'LDDID' => $ldd_file_folder_id, 'CTCLDDID' => $ctc_file_folder_id, 'status' => 1 ]; try { sleep(2); $url = url('/test/process-file'); $url = $url . "?" . http_build_query($hookParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); $response = curl_exec($ch); curl_close($ch); } catch (Exception $e) { log::error($e); } } else { log::info("No Loan; $ChildItem->Name"); } } Log::info("Processing child FINISHED"); } } } catch (Exception $e) { log::error($e); } } public function getProcessFile() { try { $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $client_conditions_folder_id = Input::get('conditionsID'); $client_guidelines_folder = Input::get('guidelinesID'); $new_loan_ref = Input::get('newLoanRefID'); $new_loan_purchase = Input::get('newLoanPurchaseID'); $client_item_id = (int)Input::get('clientItemID'); $ldd_file_folder_id = Input::get('LDDID'); $ctc_file_folder_id = Input::get('CTCLDDID'); $status = (int)Input::get('status'); $loanId = (int)Input::get('loan'); $ChildCount = (int)Input::get('count'); $query = $loanId; $CTC = false; $Conditions = false; $LDD = false; $borrowerName = null; $newDate = null; $duedate = null; $underwriter_item_id = null; $processor = null; $new_loans_embed_id = null; $conditons_embed_id = null; $uw_new_loans_embed_id = null; $new_loans_id = null; $loanlddfileid = null; $uw_ldd_folder_embed_id = null; $h_uw_ldd_folder_id = null; $uw_conditons_embed_id = null; $guidelines_embed_id = null; $uw_ldd_file_link = null; $uw_atr_file_link = null; $uw_uav_file_link = null; $token = $this->shareFileAuth(); $toSearch = ltrim($query, '0'); $response = $this->SFDataGet($token, "Items/Search?query=$toSearch&homefolderonly=false"); if (!isset($response->Results)) $response = $this->SFDataGet($token, "Items/Search?query=$toSearch&homefolderonly=false"); if (!isset($response->Results)) $response = $this->SFDataGet($token, "Items/Search?query=$toSearch&homefolderonly=false"); $search_results = $response->Results; $filtered_results = array(); $loanIdFromResult = ""; foreach ($search_results as $search_result) { if (preg_match_all("/(\d{3,})/", $search_result->FileName, $match)) { if (!empty($match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 2022, 2018))) { $loanIdFromResult = $number; } } } else { if (!($this->nBetween($match[0], 2022, 2018))) { $loanIdFromResult = $match[0]; } } $newQuery = ltrim($query, '0'); if ((int)$loanIdFromResult == (int)$query || (int)$loanIdFromResult == (int)$newQuery) { $filtered_results[] = $search_result; } } } } foreach ($filtered_results as $result) { if (($result->ParentID == $new_loan_purchase) || ($result->ParentID == $new_loan_ref)) { $new_loans_id = $result->ItemID; $new_loans_preview_link = $this->getPreviewLink($token, $new_loans_id); if ($new_loans_preview_link != null) { $new_loans_embed_url = PodioEmbed::create($attributes = array("url" => $new_loans_preview_link)); $new_loans_embed_id = $new_loans_embed_url->embed_id; } //get user details $clientDetails = $this->SFDataGet($token, "Users($result->CreatorID)"); $clientEmail = $clientDetails->Email; //get item from app using email $AppItems = PodioSearchResult::app(25683953, array( "query" => $clientEmail, "limit" => 1, )); if (!empty($AppItems)) { $processor = $AppItems[0]->id; } $fileName = $result->FileName; $fileName = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileName); $wordlist = array("Underwriting", "file", "Overlay", "Guideline", "Conventional", "Agency", "Guidelines", "UW", "pkg", "submission", "Pkg"); foreach ($wordlist as &$word) { $word = '/\b' . preg_quote($word, '/') . '\b/'; } $fileName = preg_replace($wordlist, '', $fileName); if (strpos($fileName, '_') !== false) { $fileName = str_replace("_", " ", $fileName); } $guideLineFolder = $client_guidelines_folder; $fileData = pathinfo($fileName); $extension = isset($fileData["extension"]) ? $fileData["extension"] : ""; $fileName = str_replace("." . $extension, "", $fileName); // $loanNumber = $query; if (!empty($guideLineFolder)) { list( $loanNumber, $clientName, $borrowerName, $investorName, $investorId ) = $this->extractFileNameComponent($fileName, $guideLineFolder, $query); $borrowerName = str_replace('-', "", $borrowerName); $borrowerName = trim(preg_replace('/[0-9]+/', "", $borrowerName)); } else { $borrowerName = str_replace($query, "", $fileName); $borrowerName = str_replace('-', "", $borrowerName); $borrowerName = trim(preg_replace('/[0-9]+/', "", $borrowerName)); } if ($result->ParentID == $new_loan_purchase) { $loan_type = 4; } elseif ($result->ParentID == $new_loan_ref) { $loan_type = 1; } $newDate = date("Y-m-d", strtotime($result->CreationDate)); $duedate = date("Y-m-d", strtotime('+3 weekdays', strtotime($newDate))); } else if (!empty($result->ParentName) && $result->ParentName == 'New Loans') { $uw_new_loans_folder_id = $result->ParentID; $uw_loan_file_id = $result->ItemID;; $AppItems = PodioSearchResult::app(25689843, array( "query" => $uw_new_loans_folder_id, "limit" => 1, )); if (!empty($AppItems)) { $underwriter_itemId = $AppItems[0]->id; $itemData = PodioItem::get($underwriter_itemId); $h_new_loans_folder_id = null; $uw_ldd_folder_id = null; foreach ($itemData->fields as $field) { switch ($field->external_id) { case "h-new-loans-folder-id": $h_new_loans_folder_id = $field->values; break; case "h-ldd-folder-id": $uw_ldd_folder_id = $field->values; break; case "h-conditions-folder-id": $uw_condition_folder_id = $field->values; break; } } if ($uw_new_loans_folder_id == $h_new_loans_folder_id) { $underwriter_item_id = $underwriter_itemId; $uw_new_loans_preview_link = $this->getPreviewLink($token, $uw_loan_file_id); if ($uw_new_loans_preview_link != null) { $uw_new_loans_embed_url = PodioEmbed::create($attributes = array("url" => $uw_new_loans_preview_link)); $uw_new_loans_embed_id = $uw_new_loans_embed_url->embed_id; } } } } else if (!empty($result->ParentName) && $result->ParentName == 'Condition' || $result->ParentName == 'Conditions') { if ($result->ParentID == $client_conditions_folder_id) { $Conditions = true; $conditons_item_id = $result->ItemID; $conditons_preview_link = $this->getPreviewLink($token, $conditons_item_id); if ($conditons_preview_link != null) { $conditons_embed_url = PodioEmbed::create($attributes = array("url" => $conditons_preview_link)); $conditons_embed_id = $conditons_embed_url->embed_id; } } } else if ($result->ParentID == $ctc_file_folder_id) { $CTC = true; } else if ($result->ParentID == $ldd_file_folder_id) { $LDD = true; } } foreach ($filtered_results as $result) { if (!empty($uw_ldd_folder_id)) { unset($preVdate); unset($preVATRdate); unset($preUAVRdate); if ($uw_ldd_folder_id == $result->ParentID) { $uw_ldd_folder_file_id = $result->ItemID; $uw_lddfolder_link = "https://ascentusone.sharefile.com/home/shared/$uw_ldd_folder_file_id"; $uw_ldd_folder_embed_url = PodioEmbed::create($attributes = array("url" => $uw_lddfolder_link)); $uw_ldd_folder_embed_id = $uw_ldd_folder_embed_url->embed_id; $h_uw_ldd_folder_id = $uw_ldd_folder_file_id; $get_children_uw_ldd = $this->getItemChildren($h_uw_ldd_folder_id); if (isset($get_children_uw_ldd->Children)) foreach ($get_children_uw_ldd->Children as $child) { if ($child->Name) { if (!(strpos($child->Name, 'CTC') !== false) && (strpos($child->Name, 'LDD') !== false)) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $date = strtotime($child->CreationDate); if (isset($preVdate)) { if ($date > $preVdate) { $loanlddfileid = $child->Id; $uw_ldd_file_link = "https://ascentusone.sharefile.com/document/edit/$loanlddfileid"; } } else { $loanlddfileid = $child->Id; $uw_ldd_file_link = "https://ascentusone.sharefile.com/document/edit/$loanlddfileid"; } $preVdate = $date; } } if (strpos($child->Name, 'ATR') !== false) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $ATRdate = strtotime($child->CreationDate); if (isset($preVATRdate)) { if ($ATRdate > $preVATRdate) { $uw_atr_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } } else { $uw_atr_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } $preVATRdate = $ATRdate; } } if (strpos($child->Name, 'UAV') !== false) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $UAVdate = strtotime($child->CreationDate); if (isset($preUAVRdate)) { if ($UAVdate > $preUAVRdate) { $uw_uav_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } } else { $uw_uav_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } $preUAVRdate = $UAVdate; } } } } } } if (!empty($uw_condition_folder_id)) { //echo $uw_condition_folder_id."<br>".$result->ParentID."<br>"."<br>"; if ($uw_condition_folder_id == $result->ParentID) { $uw_condition_folder_itemid = $result->ItemID; $uw_conditons_preview_link = $this->getPreviewLink($token, $uw_condition_folder_itemid); $uw_conditons_embed_url = PodioEmbed::create($attributes = array("url" => $uw_conditons_preview_link)); $uw_conditons_embed_id = $uw_conditons_embed_url->embed_id; } } if (!empty($client_guidelines_folder)) { if ($client_guidelines_folder == $result->ParentID) { $gudelines_folder_itemid = $result->ItemID; $guidelines_preview_link = $this->getPreviewLink($token, $gudelines_folder_itemid); $guidelines_embed_url = PodioEmbed::create($attributes = array("url" => $guidelines_preview_link)); $guidelines_embed_id = $guidelines_embed_url->embed_id; } } } $loanNumber = $query; if ($CTC) $status = 6; elseif ($Conditions) $status = 7; elseif ($LDD) $status = 5; $podioAttributes = array( 'client' => $client_item_id, 'loan-number' => $loanNumber . "", 'borrower-last-name' => !empty($borrowerName) ? $borrowerName : null, 'status' => array($status), 'loan-type' => !empty($loan_type) ? array($loan_type) : [], 'date-received' => !empty($newDate) ? array("start_date" => date('Y-m-d', strtotime($newDate))) : [], 'due-date' => !empty($duedate) ? array("start_date" => date('Y-m-d', strtotime($duedate))) : [], 'assigned-underwriter' => !empty($underwriter_item_id) ? $underwriter_item_id : null, 'processor' => !empty($processor) ? $processor : null, 'document-link' => !empty($new_loans_embed_id) ? $new_loans_embed_id : null, 'client-conditions-link' => !empty($conditons_embed_id) ? $conditons_embed_id : null, 'source-folder' => !empty($uw_new_loans_embed_id) ? $uw_new_loans_embed_id : null, 'loan-file-id' => !empty($new_loans_id) ? $new_loans_id : null, 'loan-ldd-file-id' => !empty($loanlddfileid) ? $loanlddfileid : null, 'uw-ldd-folder' => !empty($uw_ldd_folder_embed_id) ? $uw_ldd_folder_embed_id : [], 'h-uw-ldd-folder' => !empty($h_uw_ldd_folder_id) ? $h_uw_ldd_folder_id : null, 'uw-conditions-folder' => !empty($uw_conditons_embed_id) ? $uw_conditons_embed_id : [], 'guidelines-and-overlays' => !empty($guidelines_embed_id) ? $guidelines_embed_id : [], 'uw-ldd-file-link' => !empty($uw_ldd_file_link) ? $uw_ldd_file_link : null, 'uw-atr-file-link' => !empty($uw_atr_file_link) ? $uw_atr_file_link : null, 'uw-uav-file-link' => !empty($uw_uav_file_link) ? $uw_uav_file_link : null, ); try { $existingloantitem = PodioSearchResult::app(25688163, array( "query" => "$query", "limit" => 1, )); if (empty($existingloantitem)) { $loanNew = ltrim($query, '0'); $existingLoanItem = PodioSearchResult::app(25688163, array( "query" => "$loanNew", "limit" => 1, )); if (empty($existingLoanItem)) $response = PodioItem::create(25688163, array('fields' => $podioAttributes), array('silent' => true, 'hook' => false)); else $response = PodioItem::update($existingLoanItem[0]->id, array('fields' => $podioAttributes), array('silent' => true, 'hook' => false)); } else { $response = PodioItem::update($existingloantitem[0]->id, array('fields' => $podioAttributes), array('silent' => true, 'hook' => false)); } } catch (Exception $e) { log::info("Loan item was not created : $query"); log::error($e); } log::info("Processed file number $ChildCount - $query"); } } catch (Exception $e) { log::error("Error creating loan $query"); log::error($e); } } /** * Loop through all new loan items and sync to Podio */ public function getInitialSync() { try { $clientAppId = 25682712; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $limit = 1; $offset = (int)$_GET['offset']; $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $AppItems = PodioItem::filter($clientAppId, $attributes, $options = array()); $count = $offset; foreach ($AppItems as $appItem) { $count++; $ctc_file_folder_id = null; $ldd_file_folder_id = null; $client_conditions_folder_id = null; $client_guidelines_folder = null; $new_loan_ref = null; $new_loan_purchase = null; $new_loan_purchase2 = null; $new_loan_ref2 = null; if ($appItem->item_id) { $client_item_id = $appItem->item_id; foreach ($appItem->fields as $field) { switch ($field->external_id) { case "h-ctc-ldd-folder-id": $ctc_file_folder_id = $field->values; break; case "h-ldd-folder-id": $ldd_file_folder_id = $field->values; break; case "h-conditions-folder-id": $client_conditions_folder_id = $field->values; break; case "h-guidelines-folder-id": $client_guidelines_folder = $field->values; break; case "h-new-loan-ref-folder-id": $new_loan_ref = $field->values; break; case "h-new-loan-ref2-folder-id": $new_loan_ref2 = $field->values; break; case "h-new-loan-purchase-folder-id": $new_loan_purchase = $field->values; break; case "h-new-loan-purchase2-folder-id": $new_loan_purchase2 = $field->values; break; } } // echo $appItem->title; $testCount = 0; if (!empty($new_loan_ref)) { $getFolderChildren = $this->getItemChildren($new_loan_ref)->Children; $testCount += count($getFolderChildren); if (count($getFolderChildren) > 0) { echo "Ref items - " . count($getFolderChildren) . "<br>"; $hookParams = [ 'folder' => $new_loan_ref, 'conditionsID' => $client_conditions_folder_id, 'guidelinesID' => $client_guidelines_folder, 'newLoanRefID' => $new_loan_ref, 'newLoanPurchaseID' => $new_loan_purchase, 'clientItemID' => $client_item_id, 'LDDID' => $ldd_file_folder_id, 'CTCLDDID' => $ctc_file_folder_id, 'status' => 1 ]; try { $url = url('/test/share-file-search'); $url = $url . "?" . http_build_query($hookParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); $response = curl_exec($ch); curl_close($ch); } catch (Exception $e) { log::error($e); } } } if (!empty($new_loan_ref2)) { $getFolderChildren = $this->getItemChildren($new_loan_ref2)->Children; $testCount += count($getFolderChildren); if (count($getFolderChildren) > 0) { echo "Ref items - " . count($getFolderChildren) . "<br>"; $hookParams = [ 'folder' => $new_loan_ref2, 'conditionsID' => $client_conditions_folder_id, 'guidelinesID' => $client_guidelines_folder, 'newLoanRefID' => $new_loan_ref2, 'newLoanPurchaseID' => $new_loan_purchase, 'clientItemID' => $client_item_id, 'LDDID' => $ldd_file_folder_id, 'CTCLDDID' => $ctc_file_folder_id, 'status' => 1 ]; try { $url = url('/test/share-file-search'); $url = $url . "?" . http_build_query($hookParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); $response = curl_exec($ch); curl_close($ch); } catch (Exception $e) { log::error($e); } } } if (!empty($new_loan_purchase)) { $getFolderChildren = $this->getItemChildren($new_loan_purchase)->Children; $testCount += count($getFolderChildren); if (count($getFolderChildren) > 0) { echo "Purchase Items - " . count($getFolderChildren) . "<br>"; $hookParams = [ 'folder' => $new_loan_purchase, 'conditionsID' => $client_conditions_folder_id, 'guidelinesID' => $client_guidelines_folder, 'newLoanRefID' => $new_loan_ref, 'newLoanPurchaseID' => $new_loan_purchase, 'clientItemID' => $client_item_id, 'LDDID' => $ldd_file_folder_id, 'CTCLDDID' => $ctc_file_folder_id, 'status' => 1 ]; $url = url('/test/share-file-search'); $url = $url . "?" . http_build_query($hookParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); $response = curl_exec($ch); curl_close($ch); } } if (!empty($new_loan_purchase2)) { $getFolderChildren = $this->getItemChildren($new_loan_purchase2)->Children; $testCount += count($getFolderChildren); if (count($getFolderChildren) > 0) { echo "Purchase Items2 - " . count($getFolderChildren) . "<br>"; $hookParams = [ 'folder' => $new_loan_purchase2, 'conditionsID' => $client_conditions_folder_id, 'guidelinesID' => $client_guidelines_folder, 'newLoanRefID' => $new_loan_ref, 'newLoanPurchaseID' => $new_loan_purchase2, 'clientItemID' => $client_item_id, 'LDDID' => $ldd_file_folder_id, 'CTCLDDID' => $ctc_file_folder_id, 'status' => 1 ]; $url = url('/test/share-file-search'); $url = $url . "?" . http_build_query($hookParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); $response = curl_exec($ch); curl_close($ch); } } // echo "$appItem->title, $testCount <br>"; } } } } catch (Exception $e) { Log::error($e); } } /*sonia fntcn - initial sync for ctc ldd*/ public function getInitialSyncCtcLdd() { try { $app_id = 25682712; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $limit = 5; $offset = (int)$_GET['offset']; $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $AppItems = PodioItem::filter($app_id, $attributes, $options = array()); $count = $offset; foreach ($AppItems as $appItem) { $count++; $ldd_file_folder_id = null; $client_conditions_folder_id = null; $client_guidelines_folder = null; $new_loan_ref = null; $new_loan_purchase = null; $status = 6; if ($appItem->item_id) { $client_item_id = $appItem->item_id; foreach ($appItem->fields as $field) { switch ($field->external_id) { case "h-ctc-ldd-folder-id": $ldd_file_folder_id = $field->values; break; case "h-conditions-folder-id": $client_conditions_folder_id = $field->values; break; case "h-guidelines-folder-id": $client_guidelines_folder = $field->values; break; case "h-new-loan-ref-folder-id": $new_loan_ref = $field->values; break; case "h-new-loan-purchase-folder-id": $new_loan_purchase = $field->values; break; } } if (!empty($ldd_file_folder_id)) { $getfolderChildren = $this->getItemChildren($ldd_file_folder_id)->Children; //print_r('children count '.count($getfolderChildren)); echo "<br>"; if (count($getfolderChildren) > 0) { foreach ($getfolderChildren as $ChildItem) { $string = $ChildItem->Name; if (preg_match_all("/(\d{3,})/", $string, $match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 3000, 2000))) { $loanid = $number; } } } else { if (!($this->nBetween($match[0], 3000, 2000))) { $loanid = $match[0]; } } } if (!empty($loanid)) { $result = $this->getShareFileSearch($loanid, $client_conditions_folder_id, $client_guidelines_folder, $new_loan_ref, $new_loan_purchase, $client_item_id, $status); print_r($count); // $existingloantitem = PodioSearchResult::app(25688163, array("query" => "$loanid", // "limit" => 1, // )); // if(empty($existingloantitem)){ // echo 'This loan item is not crreated '.$loanid; // echo "<br>"; // Log::error("This loan item is not crreated in bulk upload:".$loanid .'|||'.$appItem->item_id); // } } // if(!empty($loanid)){ // $result = $this->getShareFileSearch($loanid,$client_conditions_folder_id,$client_guidelines_folder,$new_loan_ref,$new_loan_purchase); // } // $token = $this->shareFileAuth(); // $response = $this->SFDataGet($token, "Items/Search?query=$loanid&homefolderonly=false"); // print_r($response); // elseif(preg_match_all("/\d{1,2}[\.\/\-]\d{1,2}/", $string, $match)){ // $date_extract = $match[0]; // } // if(!empty($date_extract)){ // $date_removed_value = str_replace($date_extract, "",$string); // }else{ // $date_removed_value = $string; // } // if(preg_match_all("/\(([^)]+)\)/", $string, $match)){ // print_r($match); // exit; // } // $loanid = preg_replace("/[^0-9]/", '', $date_removed_value); // print_r($date_removed_value.' / '.$loanid); } } exit; } else { echo $appItem->item_id; echo "<br>"; } } } } else { echo "error"; exit; } } catch (Exception $e) { dd($e); exit; } } /*sonia fnctn - conditions folder snc*/ public function getInitialSyncConditions() { try { $app_id = 25682712; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $limit = 5; $offset = (int)$_GET['offset']; $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $AppItems = PodioItem::filter($app_id, $attributes, $options = array()); $count = $offset; foreach ($AppItems as $appItem) { $count++; $ldd_file_folder_id = null; $client_conditions_folder_id = null; $client_guidelines_folder = null; $new_loan_ref = null; $new_loan_purchase = null; $status = 7; if ($appItem->item_id) { $client_item_id = $appItem->item_id; foreach ($appItem->fields as $field) { switch ($field->external_id) { case "h-ctc-ldd-folder-id": $ldd_file_folder_id = $field->values; break; case "h-conditions-folder-id": $client_conditions_folder_id = $field->values; break; case "h-guidelines-folder-id": $client_guidelines_folder = $field->values; break; case "h-new-loan-ref-folder-id": $new_loan_ref = $field->values; break; case "h-new-loan-purchase-folder-id": $new_loan_purchase = $field->values; break; } } if (!empty($client_conditions_folder_id)) { $getfolderChildren = $this->getItemChildren($client_conditions_folder_id)->Children; print_r('children count ' . count($getfolderChildren)); echo "<br>"; if (count($getfolderChildren) > 0) { foreach ($getfolderChildren as $ChildItem) { $string = $ChildItem->Name; if (preg_match_all("/(\d{3,})/", $string, $match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 3000, 2000))) { $loanid = $number; } } } else { if (!($this->nBetween($match[0], 3000, 2000))) { $loanid = $match[0]; } } } if (!empty($loanid)) { $result = $this->getShareFileSearch($loanid, $client_conditions_folder_id, $client_guidelines_folder, $new_loan_ref, $new_loan_purchase, $client_item_id, $status); echo "<br>"; print_r($count); // $existingloantitem = PodioSearchResult::app(25688163, array("query" => "$loanid", // "limit" => 1, // )); // if(empty($existingloantitem)){ // echo 'This loan item is not crreated '.$loanid; // echo "<br>"; // Log::error("This loan item is not crreated in bulk upload:".$loanid .'|||'.$appItem->item_id); // } } // if(!empty($loanid)){ // $result = $this->getShareFileSearch($loanid,$client_conditions_folder_id,$client_guidelines_folder,$new_loan_ref,$new_loan_purchase); // } // $token = $this->shareFileAuth(); // $response = $this->SFDataGet($token, "Items/Search?query=$loanid&homefolderonly=false"); // print_r($response); // elseif(preg_match_all("/\d{1,2}[\.\/\-]\d{1,2}/", $string, $match)){ // $date_extract = $match[0]; // } // if(!empty($date_extract)){ // $date_removed_value = str_replace($date_extract, "",$string); // }else{ // $date_removed_value = $string; // } // if(preg_match_all("/\(([^)]+)\)/", $string, $match)){ // print_r($match); // exit; // } // $loanid = preg_replace("/[^0-9]/", '', $date_removed_value); // print_r($date_removed_value.' / '.$loanid); } exit; } } else { echo $appItem->item_id; echo "<br>"; } } } } else { echo "error"; exit; } } catch (Exception $e) { dd($e); exit; } } /*sonia fnctn - ldd folder snc*/ public function getInitialSyncLdd() { try { $app_id = 25682712; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $limit = 5; $offset = (int)$_GET['offset']; $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $AppItems = PodioItem::filter($app_id, $attributes, $options = array()); $count = $offset; foreach ($AppItems as $appItem) { $count++; $ldd_file_folder_id = null; $client_conditions_folder_id = null; $client_guidelines_folder = null; $new_loan_ref = null; $new_loan_purchase = null; $status = 5; if ($appItem->item_id) { $client_item_id = $appItem->item_id; foreach ($appItem->fields as $field) { switch ($field->external_id) { case "h-ctc-ldd-folder-id": $ldd_file_folder_id = $field->values; break; case "h-conditions-folder-id": $client_conditions_folder_id = $field->values; break; case "h-guidelines-folder-id": $client_guidelines_folder = $field->values; break; case "h-new-loan-ref-folder-id": $new_loan_ref = $field->values; break; case "h-new-loan-purchase-folder-id": $new_loan_purchase = $field->values; break; case "h-ldd-folder-id": $h_ldd_folder_id = $field->values; break; } } if (!empty($h_ldd_folder_id)) { $getfolderChildren = $this->getItemChildren($h_ldd_folder_id)->Children; print_r('children count ' . count($getfolderChildren)); echo "<br>"; if (count($getfolderChildren) > 0) { foreach ($getfolderChildren as $ChildItem) { $string = $ChildItem->Name; if (preg_match_all("/(\d{3,})/", $string, $match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 3000, 2000))) { $loanid = $number; } } } else { if (!($this->nBetween($match[0], 3000, 2000))) { $loanid = $match[0]; } } } if (!empty($loanid)) { // $result = $this->getUpdateLoanItems($loanid,$client_conditions_folder_id,$client_guidelines_folder,$new_loan_ref,$new_loan_purchase,$client_item_id,$status); // echo "<br>"; // print_r($count); $existingloantitem = PodioSearchResult::app(25688163, array( "query" => "$loanid", "limit" => 1, )); if (empty($existingloantitem)) { echo 'This loan item is not crreated ' . $loanid; echo "<br>"; Log::error("This loan item is not crreated in bulk upload:" . $loanid . '|||' . $appItem->item_id); } } } exit; } } else { echo $appItem->item_id; echo "<br>"; } } } } else { echo "error"; exit; } } catch (Exception $e) { dd($e); exit; } } /*sonia fnctn - update loan functon*/ public function getUpdateLoanItems($loanid, $client_conditions_folder_id, $client_guidelines_folder, $new_loan_ref, $new_loan_purchase, $client_item_id, $status) { try { $query = $loanid; $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $token = $this->shareFileAuth(); $response = $this->SFDataGet($token, "Items/Search?query=$query&homefolderonly=false"); $search_results = $response->Results; $filtered_results = array(); foreach ($search_results as $search_result) { if (preg_match_all("/(\d{3,})/", $search_result->FileName, $match)) { if (!empty($match)) { if (is_array($match[0])) { foreach ($match[0] as $number) { if (!($this->nBetween($number, 3000, 2000))) { $loanidfrom_result = $number; } } } else { if (!($this->nBetween($match[0], 3000, 2000))) { $loanidfrom_result = $match[0]; } } if ($loanidfrom_result == $query) { $filtered_results[] = $search_result; } } } } foreach ($filtered_results as $result) { if (($result->ParentID == $new_loan_purchase) || ($result->ParentID == $new_loan_ref)) { $new_loans_id = $result->ItemID; $new_loans_preview_link = $this->getPreviewLink($token, $new_loans_id); $new_loans_embed_url = PodioEmbed::create($attributes = array("url" => $new_loans_preview_link)); $new_loans_embed_id = $new_loans_embed_url->embed_id; //get user details $clientDetails = $this->SFDataGet($token, "Users($result->CreatorID)"); $clientEmail = $clientDetails->Email; //get item from app using email $userID = "601f85a08d5f4f4f615b41a2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser($userID)) { $AppItems = PodioSearchResult::app(25683953, array( "query" => $clientEmail, "limit" => 1, )); if (!empty($AppItems)) { // Processor name } } $fileName = $result->FileName; $fileName = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileName); $wordlist = array("Underwriting", "file", "Overlay", "Guideline", "Conventional", "Agency", "Guidelines", "UW", "pkg", "submission", "Pkg"); foreach ($wordlist as &$word) { $word = '/\b' . preg_quote($word, '/') . '\b/'; } $fileName = preg_replace($wordlist, '', $fileName); if (strpos($fileName, '_') !== false) { $fileName = str_replace("_", " ", $fileName); } // $loanNumber = filter_var($fileName, FILTER_SANITIZE_NUMBER_INT); $guideLineFolder = null; //Fetch from Podio client item $fileData = pathinfo($fileName); $extension = isset($fileData["extension"]) ? $fileData["extension"] : ""; $fileName = str_replace("." . $extension, "", $fileName); // $loanNumber = $query; if (!empty($guideLineFolder)) { list( $borrowerName, ) = $this->extractFileNameComponent($fileName, $guideLineFolder); $borrowerName = str_replace('-', "", $borrowerName); } else { $borrowerName = str_replace($query, "", $fileName); $borrowerName = str_replace('-', "", $borrowerName); $borrowerName = trim(preg_replace('/[0-9]+/', "", $borrowerName)); } if ($result->ParentID == $new_loan_purchase) { $loan_type = 4; } elseif ($result->ParentID == $new_loan_ref) { $loan_type = 1; } $newDate = date("Y-m-d", strtotime($result->CreationDate)); $duedate = date("Y-m-d", strtotime('+3 weekdays', strtotime($newDate))); } else if (!empty($result->ParentName) && $result->ParentName == 'New Loans') { $uw_new_loans_folder_id = $result->ParentID; $uw_loan_file_id = $result->ItemID;; $AppItems = PodioSearchResult::app(25689843, array( "query" => $uw_new_loans_folder_id, "limit" => 1, )); if (!empty($AppItems)) { $underwriter_itemId = $AppItems[0]->id; $itemData = PodioItem::get($underwriter_itemId); $h_new_loans_folder_id = null; $uw_ldd_folder_id = null; foreach ($itemData->fields as $field) { switch ($field->external_id) { case "h-new-loans-folder-id": $h_new_loans_folder_id = $field->values; break; case "h-ldd-folder-id": $uw_ldd_folder_id = $field->values; break; case "h-conditions-folder-id": $uw_condition_folder_id = $field->values; break; } } if ($uw_new_loans_folder_id == $h_new_loans_folder_id) { $underwriter_item_id = $underwriter_itemId; $uw_new_loans_preview_link = $this->getPreviewLink($token, $uw_loan_file_id); $uw_new_loans_embed_url = PodioEmbed::create($attributes = array("url" => $uw_new_loans_preview_link)); $uw_new_loans_embed_id = $uw_new_loans_embed_url->embed_id; } } } } foreach ($filtered_results as $result) { if (!empty($uw_ldd_folder_id)) { if ($uw_ldd_folder_id == $result->ParentID) { $uw_ldd_folder_file_id = $result->ItemID; $uw_lddfolder_link = "https://ascentusone.sharefile.com/home/shared/$uw_ldd_folder_file_id"; $uw_ldd_folder_embed_url = PodioEmbed::create($attributes = array("url" => $uw_lddfolder_link)); $uw_ldd_folder_embed_id = $uw_ldd_folder_embed_url->embed_id; $h_uw_ldd_folder_id = $uw_ldd_folder_file_id; $get_children_uw_ldd = $this->getItemChildren($h_uw_ldd_folder_id); foreach ($get_children_uw_ldd->Children as $child) { if ($child->Name) { if (!(strpos($child->Name, 'CTC') !== false) && (strpos($child->Name, 'LDD') !== false)) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $loanlddfileid = $child->Id; $uw_ldd_file_link = "https://ascentusone.sharefile.com/document/edit/$loanlddfileid"; } } if (strpos($child->Name, 'ATR') !== false) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $uw_atr_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } } if (strpos($child->Name, 'UAV') !== false) { $extension_info = pathinfo($child->Name, PATHINFO_EXTENSION); if ($extension_info != 'pdf') { $uw_uav_file_link = "https://ascentusone.sharefile.com/document/edit/$child->Id"; } } } } } } if (!empty($uw_condition_folder_id)) { //echo $uw_condition_folder_id."<br>".$result->ParentID."<br>"."<br>"; if ($uw_condition_folder_id == $result->ParentID) { $uw_condition_folder_itemid = $result->ItemID; $uw_conditons_preview_link = $this->getPreviewLink($token, $uw_condition_folder_itemid); $uw_conditons_embed_url = PodioEmbed::create($attributes = array("url" => $uw_conditons_preview_link)); $uw_conditons_embed_id = $uw_conditons_embed_url->embed_id; } } if (!empty($client_guidelines_folder)) { if ($client_guidelines_folder == $result->ParentID) { $gudelines_folder_itemid = $result->ItemID; $guidelines_preview_link = $this->getPreviewLink($token, $gudelines_folder_itemid); $guidelines_embed_url = PodioEmbed::create($attributes = array("url" => $guidelines_preview_link)); $guidelines_embed_id = $guidelines_embed_url->embed_id; } } } $loanNumber = $loanid; $podioAttributes = array( 'client' => $client_item_id, 'loan-number' => $loanNumber, 'borrower-last-name' => !empty($borrowerName) ? $borrowerName : null, 'status' => array($status), 'loan-type' => !empty($loan_type) ? array($loan_type) : [], 'date-received' => !empty($newDate) ? array("start_date" => date('Y-m-d', strtotime($newDate))) : [], 'due-date' => !empty($duedate) ? array("start_date" => date('Y-m-d', strtotime($duedate))) : [], 'assigned-underwriter' => !empty($underwriter_item_id) ? $underwriter_item_id : null, 'document-link' => !empty($new_loans_embed_id) ? $new_loans_embed_id : null, 'source-folder' => !empty($uw_new_loans_embed_id) ? $uw_new_loans_embed_id : null, 'loan-file-id' => !empty($new_loans_id) ? $new_loans_id : null, 'loan-ldd-file-id' => !empty($loanlddfileid) ? $loanlddfileid : null, 'uw-ldd-folder' => !empty($uw_ldd_folder_embed_id) ? $uw_ldd_folder_embed_id : [], 'h-uw-ldd-folder' => !empty($h_uw_ldd_folder_id) ? $h_uw_ldd_folder_id : null, 'uw-conditions-folder' => !empty($uw_conditons_embed_id) ? $uw_conditons_embed_id : [], 'guidelines-and-overlays' => !empty($guidelines_embed_id) ? $guidelines_embed_id : [], 'uw-ldd-file-link' => !empty($uw_ldd_file_link) ? $uw_ldd_file_link : null, 'uw-atr-file-link' => !empty($uw_atr_file_link) ? $uw_atr_file_link : null, 'uw-uav-file-link' => !empty($uw_uav_file_link) ? $uw_uav_file_link : null, ); try { $existingloantitem = PodioSearchResult::app(25688163, array( "query" => "$query", "limit" => 1, )); if (empty($existingloantitem)) { print_r($loanid); $response = PodioItem::create(25688163, array('fields' => $podioAttributes), array('silent' => true, 'hook' => false)); } } catch (Exception $e) { log::info("Loan item was not created : $query"); log::error($e); } } } catch (Exception $e) { log::info("Loan item was not created : $query"); log::error($e); } } function nBetween($varToCheck, $high, $low) { if ($varToCheck < $low) return false; if ($varToCheck > $high) return false; return true; } public function SFDataGet($token, $type) { $uri = "https://ascentusone.sf-api.com/sf/v3/" . $type; $headers = $this->get_authorization_header($token); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response // echo $http_code . "\n"; // output http status code curl_close($ch); $response = json_decode($curl_response); return $response; } public function SFDataPost($token, $type, $data = array()) { $uri = "https://ascentusone.sf-api.com/sf/v3/" . $type; $data = json_encode($data); $headers = $this->get_authorization_header($token); $headers[] = "Content-Type: application/json"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response echo "http_code = " . $http_code . "\n"; // output http status code curl_close($ch); $response = json_decode($curl_response); return $response; } public function SFDataPatch($token, $type, $data = array()) { $uri = "https://ascentusone.sf-api.com/sf/v3/" . $type; $data = json_encode($data); $headers = $this->get_authorization_header($token); $headers[] = "Content-Type: application/json"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); //echo $curl_response."\n"; // output entire response echo "http_code = " . $http_code . "\n"; // output http status code curl_close($ch); $response = json_decode($curl_response); return $response; } public function getExisting() { try { $token = $this->shareFileAuth(); $ExistingHooks = $this->SFDataGet($token, "WebhookSubscriptions"); print_r($ExistingHooks); } catch (Exception $e) { dd($e); exit; } } public function getTestAuth() { try { echo "<pre>"; $uri = "https://ascentusone.sharefile.com/oauth/token"; $body_data = array( "grant_type" => "password", "client_id" => "21R0WJBkEJHyVf33xVH73KIhoo7skDLW", "client_secret" => "9PbF1xqFDLWjenYVAezgbbfF2GcQ0tnrKo8Ew4sdjYjuEe1z", "username" => "podio@ascentus1.com", "password" => "jjyh insc o5vt mqts" ); $data = http_build_query($body_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded')); $curl_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error_number = curl_errno($ch); $curl_error = curl_error($ch); curl_close($ch); $token = NULL; if ($http_code == 200) { $token = json_decode($curl_response); // $this->get_item_by_id($token,"fod08b81-6ad5-4e45-82ab-39ea7e0bcdc8"); $this->get_shares($token); } } catch (Exception $e) { dd($e); exit; } } function get_authorization_header($token) { return array("Authorization: Bearer " . $token->access_token); } function get_hostname($token) { return $token->subdomain . ".sf-api.com"; } public function getAppRelations() { $userID = "5e342d3fb5008837733e2ea7"; $userID = "556c4e4a21b4d648635ce70d"; $authRepo = new AuthRepository(); try { if ($authRepo->authenticateUser($userID)) { $appID = 18181607; $appRelations = PodioApp::dependencies($appID); // $app = PodioApp::get( $appID, $attributes = array() ); dd($appRelations); } } catch (Exception $e) { dd($e); exit; } } public function getTestArray() { $userID = "614b0ec107266f0fa9466c02"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { echo "Auth Yes"; } else { echo "Auth No"; } } public function getTestNew() { exit; $userID = "599e89a2b500883e209fa379"; $authRepo = new AuthRepository(); echo "<pre>"; if ($authRepo->authenticateUser($userID)) { try { // Clone app without items // try { // $toBeClonedAppId = 14378191; // $targetWorkSpace = 4798681; // $activeFields = array(); // $app = PodioApp::get($toBeClonedAppId); // foreach ($app->fields as $field) { // if ($field->status == "active") { // array_push($activeFields, $field->external_id); // } // } // $newAppId = PodioApp::install($toBeClonedAppId, $attributes = array( // "space_id" => $targetWorkSpace, "features" => array('votings', 'integration', 'flows', 'forms', 'filters', 'widgets') // )); // log::info($newAppId); // print_r($newAppId); // print_r($activeFields); // exit; // } catch (Exception $e) { // Log::error($e); // exit; // } $activeFields = array( 'title', 'link', 'type', 'unit', 'status', 'owner-text', 'owner', 'cost-year', 'cost-type', 'credit-card-used', 'payment-terms', 'account-handling-google-login', 'account-handling-other' ); $toBeClonedAppId = 14378191; $targetWorkSpace = 4798681; $newAppId = 19241494; if ($newAppId) { try { // get all the item from the new app $limit = 200; $offset = 0; do { $attributes = array( 'sort_asc' => true, 'limit' => $limit, 'offset' => $offset ); $itemCollection = PodioItem::filter($toBeClonedAppId, $attributes, $options = array()); $count = count($itemCollection); foreach ($itemCollection as $item) { $podioFields = array(); foreach ($item->fields as $field) { if (in_array($field->external_id, $activeFields)) switch ($field->type) { case 'embed': foreach ($field->values as $values) { $fileID = PodioEmbed::create($attributes = array("url" => $values->resolved_url)); $podioFields[$field->external_id][] = array("embed" => $fileID->embed_id); } break; case 'image': foreach ($field->values as $values) { try { $fileID = PodioFile::copy($values->file_id); } catch (Exception $e) { log::error("No rights to add prev image"); } if (isset($fileID)) $podioFields[$field->external_id][] = array("value" => $fileID->file_id); } break; case 'date': $dateObject = true; if (isset($field->values)) { if (array_key_exists("start", $field->values)) { $dateValue = true; } else { $dateObject = false; } } if ($dateObject) { $startDate = null; $startTime = null; $endDate = null; $endTime = null; $start = null; $end = null; $valArray = array(); if (isset($field->values)) { if (is_array($field->values)) { $start = $field->values['start']; if ($field->values['end']) $end = $field->values['end']; } else { $start = $field->values->start; if ($field->values->end) $end = $field->values->end; } if ($start) { $startDate = $this->formatDate($start->format('Y-m-d'), $userID); if ($dateValue) $startTime = $this->formatTime($start->format('H:i:s'), $userID); if ($end) { $endDate = $this->formatDate($end->format('Y-m-d'), $userID); if ($dateValue) $endTime = $this->formatTime($end->format('H:i:s'), $userID); $podioFields[$field->external_id] = array("start_date" => $startDate, "start_time" => $startTime, "end_date" => $endDate, "end_time" => $endTime); } else { $podioFields[$field->external_id] = array("start_date" => $startDate, "start_time" => $startTime); } } } } break; case 'category': $catValues = array(); foreach ($field->values as $values) { array_push($catValues, $values['id']); } $podioFields[$field->external_id] = $catValues; break; case 'contact': $conValues = array(); foreach ($field->values as $values) { $ignoreUser = false; try { $spaceMember = PodioSpaceMember::get($targetWorkSpace, $values->user_id); } catch (Exception $e) { } if (isset($spaceMember) && !$spaceMember->role . '') { $ignoreUser = true; } if (!$ignoreUser) array_push($conValues, $values->profile_id); } $podioFields[$field->external_id] = $conValues; break; case 'app': $appValues = array(); foreach ($field->values as $values) { array_push($appValues, $values->item_id); } $podioFields[$field->external_id] = $appValues; break; default: if ($field->type != "calculation" && $field->type != "app") { try { $podioFields[$field->external_id] = $field->values; } catch (Exception $e) { print_r($field); } } break; } } $itemData = PodioItem::get($item->item_id); $fileIDs = array(); if ($itemData->files) { foreach ($itemData->files as $file) { try { $fileCopy = PodioFile::copy($file->file_id); array_push($fileIDs, $fileCopy->file_id); } catch (Exception $e) { log::error("Can not copy Podio Files for item"); } } } if (count($fileIDs) > 0) { $podioAttributes = array('file_ids' => $fileIDs, 'fields' => array_filter($podioFields)); } else { $podioAttributes = array('fields' => array_filter($podioFields)); } $response = PodioItem::create($newAppId, $podioAttributes, array('silent' => true)); $id = $response->item_id; $tag = array(); if ($itemData->tags) { foreach ($itemData->tags as $tags) { $tag[] = $tags; } try { PodioTag::create('item', $id, $tag); } catch (Exception $e) { log::error("Tag cannot be added in item " . $id); } } $data = array( "item_id" => $id, 'old_item_id' => $item->item_id, 'src_space_id' => 3906164, 'tgt_space_id' => 4798681, 'new_app_id' => 19241494, 'queue_id' => "59a3dc33b500882773119532", 'save_item_relation_status' => 'not_saved', 'ref_update_status' => 'not_updated', 'comment_status' => 'not_completed', 'task_status' => 'not_completed' ); $this->itemModel->create($data); } exit; $offset += $limit; } while ($count >= $limit); } catch (Exception $e) { Log::error($e); } } } catch (Exception $e) { print_r($e); exit; } } } public function formatDate($value, $userID) { $user = $this->user->findOne(array('_id' => $userID)); $UTC = new DateTimeZone("UTC"); $newTZ = new DateTimeZone("UTC"); $date = new DateTime($value, $UTC); $date->setTimezone($newTZ); return $date->format('Y-m-d'); } public function formatTime($value, $userID) { $user = $this->user->findOne(array('_id' => $userID)); $UTC = new DateTimeZone("UTC"); $newTZ = new DateTimeZone("UTC"); $date = new DateTime($value, $UTC); $date->setTimezone($newTZ); return $date->format('H:i:s'); } public function syncCalculationFields($userId = null, $queueId = null) { if ($this->authRepo->authenticateUser($userId)) { $calculationRepo = new CalculationRepo(); $podioAppsModel = new PodioAppModel(); $apps = $podioAppsModel->find(array('queue_id' => $queueId)); $count = 0; if ($apps) { foreach ($apps as $app) { $missingFields = $this->arrayDiff($app['fields'], $app['new_fields']); $count += count($missingFields); foreach ($missingFields as $field) { if ($field['type'] == 'calculation') { $newScript = $calculationRepo->getNewScript($app, $field['script'], null); // update calculation field. try { $attributes = array("type" => 'calculation', 'config' => array( 'label' => $field['label'], 'delta' => $field['delta'], 'settings' => array('script' => $newScript) )); $resp = PodioAppField::create($app['new_app_id'], $attributes); $appFields = $app['fields']; $newFields = $app['new_fields']; $newFields[] = array( "type" => 'calculation', 'label' => $field['label'], 'external_id' => $field['external_id'], 'field_id' => intval($resp) ); $podioAppsModel->update(array('_id' => $app['_id']), array('fields' => $appFields, 'new_fields' => $newFields)); } catch (Exception $e) { Log::error($e); } } } } } } echo "<br/><br/>COUNTTTTTTTT:" . $count; } public function getUpdateMissingFlow() { $userID = "5b65f33eb500889835002519"; $itemRepo = new ItemRepo(); $authRepo = new AuthRepository(); $podioAppsModel = new PodioAppModel(); $apps = $podioAppsModel->find(array('queue_id' => "5b65f68cb500880d39002519")); $count = 0; if ($this->authRepo->authenticateUser($userID)) { if ($apps) { foreach ($apps as $app) { try { if (isset($app['flows'])) { $flows = $app['flows']; foreach ($flows as $flow) { $newFlow = array(); $newFlow['type'] = $flow['type']; $newFlow['name'] = $flow['name']; $newFlow['config'] = array(); if (!empty($flow['config']['field_ids'])) { if (is_array($flow['config']['field_ids']) or ($flow['config']['field_ids'] instanceof Traversable)) { $newFlow['config']['field_ids'] = array(); foreach ($flow['config']['field_ids'] as $fieldId) { try { $field = PodioAppField::get($app['app_id'], $fieldId); $externalId = $field->external_id; $newField = PodioAppField::get($app['new_app_id'], $externalId); $newFieldId = $newField->field_id; array_push($newFlow['config']['field_ids'], $newFieldId); } catch (Exception $e) { log::error($e); } } } } if (!empty($flow['config']['conditions'])) { if (is_array($flow['config']['conditions']) or ($flow['config']['conditions'] instanceof Traversable)) { $newFlow['config']['conditions'] = array(); foreach ($flow['config']['conditions'] as $condition) { $conditionField = $condition['field_id']; try { $field = PodioAppField::get($app['app_id'], $conditionField); $externalId = $field->external_id; $newField = PodioAppField::get($app['new_app_id'], $externalId); $newFieldId = $newField->field_id; $condition['field_id'] = $newFieldId; array_push($newFlow['config']['conditions'], $condition); } catch (Exception $e) { log::error($e); } } } } $newFlow['effects'] = array(); foreach ($flow['effects'] as $effect) { $addEffect = true; $newEffect = array(); $newEffect['type'] = $effect['type']; $newEffect['attributes'] = $effect['attributes']; if ($newEffect['type'] == "taskreplace_dot_dotcreate") { $assignedUser = $effect['attributes'][1]['value']; if (is_numeric($assignedUser)) { try { $spaceUser = PodioSpaceMember::get($app['target_space_id'], $assignedUser); if (is_null($spaceUser->role)) { $newEffect['attributes'][1] = array( "nullable" => false, "required" => false, "value" => "{{global.auth}}", "label" => "Assign to", "attribute_id" => "task.responsible", "substitutions" => array( "{{global.auth}}" => "Current user or app" ), "type" => "user" ); } } catch (Exception $e) { $newEffect['attributes'][1] = array( "nullable" => false, "required" => false, "value" => "{{global.auth}}", "label" => "Assign to", "attribute_id" => "task.responsible", "substitutions" => array( "{{global.auth}}" => "Current user or app" ), "type" => "user" ); } } } foreach ($newEffect['attributes'] as $arrayIndex => $attribute) { foreach ($attribute as $index => $value) if ($value == "" || (is_array($value) && count($value) == 0)) { if ($index == "nullable" || $index == "required") $newEffect['attributes'][$arrayIndex][$index] = 0; elseif ($index != "substitutions") unset($newEffect['attributes'][$arrayIndex][$index]); } } $newEffect['attributes'] = array_values($newEffect['attributes']); if (array_key_exists('config', $effect) && $effect['config'] != null) { $newEffect['config'] = $effect['config']; if (is_array($newEffect['config'])) { $oldRefAppId = $newEffect['config']['app']['app_id']; $oldRefFieldId = $newEffect['config']['field']['field_id']; $newFieldId = ""; $appIdToUse = ""; $newApp = $podioAppsModel->findOne(array('app_id' => (int)$oldRefAppId, 'queue_id' => $app['queue_id'])); if ($newApp['relational_fields'] && count($newApp['relational_fields'])) { foreach ($newApp['relational_fields'] as $relation) { if ($relation['field_id'] == $oldRefFieldId) { $appIdToUse = $newApp['new_app_id']; $newFieldId = $relation['new_field_id']; } } } if ($newFieldId == "") { if ($app['relational_fields'] && count($app['relational_fields'])) { foreach ($app['relational_fields'] as $relation) { if ($relation['field_id'] == $oldRefFieldId) { $appIdToUse = $app['new_app_id']; $newFieldId = $relation['new_field_id']; } } } } try { $newAppDetails = PodioApp::get($newApp['new_app_id'], array('type' => 'Mini')); $newFieldDetails = PodioAppField::get($appIdToUse, $newFieldId); $newEffect['config']['field'] = $newFieldDetails; $newEffect['config']['app'] = $newAppDetails; } catch (Exception $e) { $addEffect = false; log::error($e); } } } if ($addEffect) array_push($newFlow['effects'], $newEffect); } if (isset($newFlow)) { $newFlow = (array)$newFlow; $newFlow = array_filter($newFlow); $newFlow = $this->utf8enc($newFlow); $newFlow = (array)$newFlow; try { $resp = PodioFlow::create('app', $app['new_app_id'], $newFlow); echo "SUCCESS"; echo "<br>"; } catch (Exception $e) { log::error($e); echo "FAILED"; echo "<br>"; } } } } //update } catch (Exception $e) { log::error($e); } } } } } public function utf8enc($array_to_encode) { $encoded_array = array(); if (is_array($array_to_encode)) { foreach ($array_to_encode as $key => $value) { if (is_array($value) || $value instanceof Traversable) { $encoded_array[strpos($key, 'replace_dot_dot') ? str_replace('replace_dot_dot', '.', $key) : $key] = $this->utf8enc((array)$value); } else { $encoded_array[strpos($key, 'replace_dot_dot') ? str_replace('replace_dot_dot', '.', $key) : $key] = strpos($value, 'replace_dot_dot') ? str_replace('replace_dot_dot', '.', $value) : $value; } } } return $encoded_array; } public function getJoeTest() { $userId = "603e4c3503c7d269194bbdf2"; $result = array(); $result['spaces'] = array(); $totalAmount = 0; $appStructureOnly = false; $spaceRes = array(); if ($this->authRepo->authenticateUser($userId)) { $apps = PodioApp::get_for_space(2391465); if ($apps != false && count($apps)) { foreach ($apps as $app) { $avoidApp = false; $getApp = Podio::get("/app/$app->app_id")->json_body(); foreach ($getApp['fields'] as $field) { if (!$avoidApp) if ($field['type'] == 'contact' && $field['status'] == 'active') { if ($field['config']['settings']['type'] == 'space_contacts') { echo '*********************************' . $app->config['name'] . '<br/>'; $avoidApp = true; } } } if (!$avoidApp) { $appRes = array(); $appRes['name'] = $app->config['name']; echo $appRes['name'] . '<br/>'; if ($appStructureOnly == true) { $itemCount = 0; } else $itemCount = PodioItem::get_count($app->app_id); $appRes['itemCount'] = ($itemCount) ? $itemCount : 0; $totalAmount += ($appRes['itemCount'] * Config::$ITEM_PRICE); $taskCount = Podio::get("/task/app/$app->app_id/count"); $taskCount = json_decode($taskCount->body); $appRes['taskCount'] = $taskCount->count; $spaceRes['apps'][] = $appRes; } } dd($spaceRes); } } dd(count($apps)); } // https://podiocopy.phases.dk/test/test-process public function getTestProcess() { try { echo "<pre>"; $queueID = "641997123400fb351c2573c2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser()) { $missedItemId = 1546433321; //for test $newItemId = 2417441026; //for test //get app items $oldAppId = 25290772; $attributes = []; $oldAppItems = PodioItem::filter($oldAppId, $attributes, $options = array()); $oldAppItemIds = []; foreach ($oldAppItems as $oldItem) { $oldAppItemIds[] = $oldItem->item_id; } $newAppId = 28465231; $_attributes = []; $newAppItems = PodioItem::filter($newAppId, $_attributes, $options = array()); $newAppItemExIds = []; foreach ($newAppItems as $newItem) { $newAppItemExIds[] = str_replace("share_", "", $newItem->external_id); } $missedItemIds = array_diff($oldAppItemIds, $newAppItemExIds); $missedItemIds = [1546433321]; //for test if (!empty($missedItemIds)) { foreach ($missedItemIds as $missedItemId) { $externalId = "share_" . $missedItemId; $itemData = $this->podioAppsModel->findOne(array('queue_id' => $queueID, 'app_id' => $oldAppId)); $newItemId = null; $newItemId = 2417441026; //for test $podioAttributes = []; $fieldRelations = []; foreach ($itemData->fields as $field) { $field_id = $field->field_id; $fieldValues = PodioItem::get_field_value($missedItemId, $field_id); if ($fieldValues) { //types - embed,duration,location,progress,money,contact,member,app,date,image,number,text,category,email,phone switch ($field->type) { case "contact": foreach ($fieldValues as $fieldValue) { $podioAttributes[$field->external_id][] = $fieldValue['value']['profile_id']; } break; case "email": foreach ($fieldValues as $fieldValue) { $podioAttributes[$field->external_id][] = array("type" => $fieldValue['type'], "value" => $fieldValue['value']); } break; case "phone": foreach ($fieldValues as $fieldValue) { $podioAttributes[$field->external_id][] = array("type" => $fieldValue['type'], "value" => $fieldValue['value']); } break; case "date": $start = isset($fieldValues[0]['start']) ? $fieldValues[0]['start'] : null; $end = isset($fieldValues[0]['end']) ? $fieldValues[0]['end'] : null; $podioAttributes[$field->external_id] = ["start" => $start, "end" => $end]; break; case "embed": foreach ($fieldValues as $fieldValue) { $embedID = PodioEmbed::create(array("url" => $fieldValue['embed']['resolved_url'])); $podioAttributes[$field->external_id][] = array("embed" => $embedID->embed_id); } break; case "image": foreach ($fieldValues as $fieldValue) { $fileID = PodioFile::copy($fieldValue['value']['file_id']); if (isset($fileID)) $podioAttributes[$field->external_id][] = array("value" => $fileID->file_id); } break; case "category": foreach ($fieldValues as $fieldValue) { $podioAttributes[$field->external_id][] = $fieldValue['value']['id']; } break; case "calculation": break; case "money": $podioAttributes[$field->external_id][] = array("currency" => $fieldValues[0]['currency'], "value" => $fieldValues[0]['value']); break; case "app": // if (isset($fieldValues->item_id)) { // if (!array_key_exists($field->external_id, $fieldRelations)) { // $fieldRelations[$field->external_id] = array(); // } // $fieldRelations[$field->external_id][] = array( // 'external_id' => $field->external_id, // 'ref_item_id' => $fieldValues->item_id, // 'ref_app_id' => $fieldValues->app->app_id, // 'source_field_id' => $field->field_id // ); // } break; default: $podioAttributes[$field->external_id] = $fieldValues[0]['value']; break; } } if (!$newItemId) { $response = PodioItem::create( $newAppId, array('fields' => $podioAttributes, 'external_id' => $externalId), $options = array() ); $newItemId = $response->item_id; if ($newItemId) return 'New item created with itemId : ' . $newItemId; } else { $update = PodioItem::update($newItemId, array('fields' => $podioAttributes)); if ($update) return 'Item updated'; } } // dd($podioAttributes); } } } } catch (Exception $e) { Log::error($e); } } // https://podiocopy.phases.dk/test/paid-list?range=last-1-month public function getPaidList() { try { $input = Input::all(); $date_range = isset($input['range']) ? $input['range'] : ''; // Retrieve the current date $current_date = strtotime(date("Y-m-d")); $date_from = null; if ($date_range) { switch ($date_range) { case"last-1-month": // Retrieve the date and time 1 month ago $date_from = strtotime(date('Y-m-d', strtotime('-1 month', $current_date))); break; case"last-3-month": // Retrieve the date and time 3 months ago $date_from = strtotime(date('Y-m-d', strtotime('-3 month', $current_date))); break; case"last-6-month": // Retrieve the date and time 6 months ago $date_from = strtotime(date('Y-m-d', strtotime('-6 month', $current_date))); break; case"last-1-year": // Retrieve the date and time 1 year ago $date_from = strtotime(date('Y-m-d', strtotime('-1 year', $current_date))); break; } } $phases_pay = new PhasesPay(); $query = array('status' => 'processed'); if ($date_from != null) { $query['createdTime'] = array('$gte' => $date_from); } $results = $phases_pay->find($query); $total_amount = 0; if ($results) { echo '<br>'; // echo '<p style="padding-left:5%";><b>Date range from : </b>'.date("d-m-Y",$date_from).' to '. date("d-m-Y",$current_date).'</p>'; echo '<br>'; echo '<table style="padding-left:5%";>'; echo '<tr>'; echo '<th style="text-align:left;"> Name</th>'; echo '<th style="text-align:left;"> Email</th>'; echo '<th style="text-align:left;">Date</th>'; echo '<th style="text-align:right;">Amount</th>'; echo '</tr>'; echo '<tr></tr>'; foreach ($results as $result) { echo '<tr>'; echo '<td width="20%">' . $result['customerName'] . '</td>'; echo '<td width="30%">' . $result['customerEmail'] . '</td>'; echo '<td width="10%">' . date("d-m-Y", $result['createdTime']) . '</td>'; echo '<td style=" text-align: right;" width="10%">' . sprintf('%0.2f', $result['TotalAmountToCharge']) . '</td>'; echo '</tr>'; $total_amount = $total_amount + $result['TotalAmountToCharge']; } echo '<tr><td colspan="3"></td></tr>'; echo '<tr><td></td><td><b>Total Amount </b></td><td></td><td style=" text-align: right;"><b>' . sprintf('%0.2f', $total_amount) . '</b></td></tr>'; echo '</table>'; echo '<br><br><br>'; // echo 'Total Amount : '. $total_amount; } else { echo 'No result found'; } } catch (Exception $e) { Log::error($e); } } // https://podiocopy.phases.dk/test/queue-list?range=last-1-month public function getQueueList() { try { // dd("queue-data"); $input = Input::all(); $date_range = ''; if ($input && isset($input['range'])) { $date_range = $input['range']; } // Retrieve the current date $current_date = strtotime(date("Y-m-d")); $date_from = null; if ($date_range) { switch ($date_range) { case"last-1-month": // Retrieve the date and time 1 month ago $date_from = strtotime(date('Y-m-d', strtotime('-1 month', $current_date))); break; case"last-3-month": // Retrieve the date and time 3 months ago $date_from = strtotime(date('Y-m-d', strtotime('-3 month', $current_date))); break; case"last-6-month": // Retrieve the date and time 6 months ago $date_from = strtotime(date('Y-m-d', strtotime('-6 month', $current_date))); break; case"last-1-year": // Retrieve the date and time 1 year ago $date_from = strtotime(date('Y-m-d', strtotime('-1 year', $current_date))); break; } } $query = array('$or' => array(array('payment_type' => array('$exists' => false)), array('payment_type' => array('$ne' => 'trial')) )); if ($date_from != null) { $query['createdTime'] = array('$gte' => $date_from); } $tQ = new TransferQueue(); $results = $tQ->find($query); $total_amount = 0; if ($results) { echo '<br>'; // echo '<p style="padding-left:5%";><b>Date range from : </b>'.date("d-m-Y",$date_from).' to '. date("d-m-Y",$current_date).'</p>'; echo '<br>'; echo '<table style="padding-left:5%";>'; echo '<tr>'; // echo '<th style="text-align:left;"> Name</th>'; echo '<th style="text-align:left;">Date</th>'; echo '<th style="text-align:right;">Amount</th>'; echo '</tr>'; echo '<tr></tr>'; foreach ($results as $result) { echo '<tr>'; // if($result['src_org']){ // echo '<td width="20%">'.$result['src_org'].'</td>'; // } // else{ // } echo '<td width="20%">' . date("d-m-Y", $result['createdTime']) . '</td>'; if (isset($result['amount'])) { echo '<td style=" text-align: right;" width="10%">' . sprintf('%0.2f', $result['amount']) . '</td>'; } else { echo '<td style=" text-align: right;" width="10%"></td>'; } echo '</tr>'; if (isset($result['amount'])) { $total_amount = $total_amount + $result['amount']; } } echo '<tr><td colspan="3"></td></tr>'; echo '<tr><td><b>Total Amount </b></td><td style=" text-align: right;"><b>' . sprintf('%0.2f', $total_amount) . '</b></td></tr>'; echo '</table>'; echo '<br><br><br>'; } else { echo 'No result found'; } } catch (Exception $e) { Log::error($e); } } // https://podiocopy.phases.dk/test/copy-item-data public function getCopyItemData() { try { Log::info("-------------Start-------------------"); echo "<pre>"; $userId = "63650a48b056a755aa7a95b2"; $authRepo = new AuthRepository(); if ($authRepo->authenticateUser()) { $limit = 500; $offset = 2; $newAppId = 26376897; $sourceAppId = 25917608; $itemCount = 0; do { $created_date = date('2023-04-26'); $attributes = array( 'filters' => array( 'created_on' => array('from' => $created_date . " 00:00:00", 'to' => $created_date . " 23:59:59"), //'next-action' => 52 'created_via' => 57, ), 'limit' => $limit, 'offset' => $offset); $itemCollection = PodioItem::filter($newAppId, $attributes, $options = array()); Log::info("filter count : " . $itemCollection->filtered); $count = count($itemCollection); //dd($itemCollection->filtered); if ($count > 0) { foreach ($itemCollection as $item) { Log::info("new itemId : " . $item->item_id); $itemCount = $itemCount + 1; $itemArray = []; $itemArray['item_id'] = $item->item_id; $itemFields = $item->fields; foreach ($itemFields as $field) { switch ($field->external_id) { case 'source-item-id-hidden': Log::info("source-item-id-hidden : " . $field->values); $oldItemData = PodioItem::get_by_app_item_id($sourceAppId, (int)Strip_tags($field->values)); $itemArray['old_item_id'] = $oldItemData->item_id; Log::info("old itemId : " . $oldItemData->item_id); //update first comment in the new item $attributes_values = array('limit' => 1, 'offset' => 0); $first_comment = PodioComment::get_for('item', $itemArray['item_id'], $attributes_values); // get first comment value if ($first_comment && isset($first_comment[0])) { $comment_id = $first_comment[0]->comment_id; $commentAttributes['value'] = "*Item created by [" . $oldItemData->created_by->name . '](' . $oldItemData->created_by->url . ') on ' . date('Y-m-d H:i:s', $oldItemData->created_on->getTimestamp()) . '(UTC)*' . PHP_EOL; PodioComment::update($comment_id, $commentAttributes); } else { Log::info("comment not found for item : " . $itemArray['item_id']); } /*$appRepo = new AppToAppItemRepo(); //copy comments Log::info("----copy comments--------"); $itemArray['item_created_by_comment'] = "*Item created by [" . $oldItemData->created_by->name . '](' . $oldItemData->created_by->url . ') on ' . date('Y-m-d H:i:s', $oldItemData->created_on->getTimestamp()) . '(UTC)*' . PHP_EOL; $appRepo->copyComments($itemArray,false,null,true); //copy task Log::info("-------copy task-------"); $itemArray['shareItem'] = 'true'; $appRepo->copyTasks($itemArray,false,false,null,true); //copy files Log::info("----------copy files----------"); $this->copyFiles($itemArray); //$this->copyItemImages($itemArray);*/ break; } } } } Log::info("itemCount : " . $itemCount); Log::info("offset : " . $offset); $offset += $limit; } while ($count >= $limit); Log::info("-------------END-------------------"); } echo "process completed"; } catch (Exception $e) { Log::error($e); dd("Exception Error"); } } public function copyFiles($item) { $itemData = PodioItem::get($item['old_item_id']); $files = $itemData->files; $fileIDs = array(); if (count($files) > 0) { foreach ($files as $file) { try { $fileCopy = PodioFile::copy($file->file_id); array_push($fileIDs, $fileCopy->file_id); } catch (Exception $e) { Log::error("Can not copy Podio Files for item"); } } if (count($fileIDs) > 0) { try { $podioAttributes = array('file_ids' => $fileIDs); PodioItem::update($item['item_id'], $podioAttributes, array('silent' => true)); } catch (Exception $e) { Log::error("Podio Files update Exception : " . $e); } Log::info("process copyFiles end "); } else { Log::info("no files"); } } else { Log::info("no files in item : " . $item['old_item_id']); } } public function copyItemImages($item) { try { $itemData = PodioItem::get($item['old_item_id']); $podioAttributes = []; foreach ($itemData->fields as $field) { switch ($field->type) { case "image": $field_id = $field->field_id; $fieldValues = PodioItem::get_field_value($item['old_item_id'], $field_id); if (count($fieldValues)) { foreach ($fieldValues as $fieldValue) { $fileID = PodioFile::copy($fieldValue['value']['file_id']); if (isset($fileID)) { $podioAttributes[$field->external_id][] = array("value" => $fileID->file_id); } } if ($item['item_id']) { $update = PodioItem::update($item['item_id'], array('fields' => $podioAttributes)); if ($update) { Log::info("success"); } } } break; } } } catch (Exception $e) { Log::error("Exception : " . $e); } } public function copyRelation($item) { try { $oldItemData = PodioItem::get($item['old_item_id']); $podioAttributes = []; foreach ($oldItemData->fields as $field) { switch ($field->external_id) { case 'fiche-inscription-master': case 'departement-de-naissance-2': case 'departement-de-residence': $podioAttributes[$field->external_id] = []; foreach ($field->values as $value) { if (isset($value->item_id)) { array_push($podioAttributes[$field->external_id], $value->item_id); } } break; } } if (!empty($podioAttributes)) { $update = PodioItem::update($item['item_id'], array('fields' => $podioAttributes)); if ($update) { Log::info("success"); } } } catch (Exception $e) { Log::error("Exception : " . $e); } } // https://podiocopy.phases.dk/test/copy-missing-item-check public function getCopyMissingItemCheck() { try { $email = "podio@eurus-europe.com"; $userMdl = new User(); $user = $userMdl->findOne(array('email' => $email)); if ($user) { $userId = $user->_id; if ($this->authRepo->authenticateUser($userId)) { $oldAppId = 21451024; $newAppId = 28615556; /** ------get old itemIds start ----- */ $limit = 200; $offset = 0; $count = 0; $oldAppItemIds = []; do { $attributes = array( 'limit' => $limit, 'offset' => $offset ); $oldAppItems = PodioItem::filter($oldAppId, $attributes, $options = array()); $count = count($oldAppItems); Log::info("filter count : " . $oldAppItems->filtered); foreach ($oldAppItems as $oldItem) { $oldAppItemIds[] = $oldItem->item_id; } $offset += $limit; } while ($count >= $limit); Log::info(" oldAppItemcount : " . count($oldAppItemIds)); /** ------ get old itemIds end ----- */ /** ------get new itemIds start ----- */ $_limit = 200; $_offset = 0; $_count = 0; $newAppItemExIds = []; do { $_attributes = array( 'limit' => $_limit, 'offset' => $_offset ); $newAppItems = PodioItem::filter($newAppId, $_attributes, $options = array()); $_count = count($newAppItems); Log::info("filter count : " . $newAppItems->filtered); foreach ($newAppItems as $newItem) { $newAppItemExIds[] = str_replace("share_", "", $newItem->external_id); } Log::info(" newAppItemcount : " . count($newAppItemExIds)); $_offset += $_limit; } while ($_count >= $_limit); /** ------ get new itemIds end ----- */ $missedItemIds = array_diff($oldAppItemIds, $newAppItemExIds); Log::info(" missedAppItemcount : " . count($missedItemIds)); dd($missedItemIds); // $limit_count = 0; // if (!empty($missedItemIds)) { // foreach ($missedItemIds as $missedItemId) { // Log::info(" limit_count : " . $limit_count); // $newItemId = null; // $itemArray = []; // $itemArray['old_item_id'] = $missedItemId; // Log::info("old item id : ".$missedItemId); // $externalId = "share_" . $missedItemId; // $itemData = PodioItem::get($missedItemId); // if(isset($itemData->fields)){ // foreach ($itemData->fields as $field) { // $podioAttributes = []; // $fieldValues = $field->values; // if ($fieldValues) { // //types - embed,duration,location,progress,money,contact,member,app,date,image,number,text,category,email,phone // switch ($field->type) { // case "contact": // foreach ($fieldValues as $fieldValue) { // $podioAttributes[$field->external_id][] = $fieldValue->profile_id; // } // break; // case "email": // foreach ($fieldValues as $fieldValue) { // $podioAttributes[$field->external_id][] = array("type" => $fieldValue['type'], "value" => $fieldValue['value']); // } // break; // case "phone": // foreach ($fieldValues as $fieldValue) { // $podioAttributes[$field->external_id][] = array("type" => $fieldValue['type'], "value" => $fieldValue['value']); // } // break; // case "date": // $startDate = null; // $startTime = null; // $endDate = null; // $endTime = null; // if (is_array($fieldValues)) { // if (isset($fieldValues['start'])) { // $startDate = $this->formatDate_1($fieldValues['start']->format('Y-m-d'), $userId); // $sTime = $fieldValues['start']->format('H:i:s'); // if ($sTime != "00:00:00") { // $startTime = $this->formatTime_1($fieldValues['start']->format('H:i:s'), $userId); // } // } // if (isset($fieldValues['end'])) { // $endDate = $this->formatDate_1($fieldValues['end']->format('Y-m-d'), $userId); // $eTime = $fieldValues['end']->format('H:i:s'); // if ($eTime != "00:00:00") { // $endTime = $this->formatTime_1($fieldValues['end']->format('H:i:s'), $userId); // } // } // } // $podioAttributes[$field->external_id] = array("start_date" => $startDate, "start_time" => $startTime, "end_date" => $endDate, "end_time" => $endTime); // break; // case "embed": // foreach ($fieldValues as $fieldValue) { // $embedID = PodioEmbed::create(array("url" => $fieldValue->resolved_url)); // $podioAttributes[$field->external_id][] = array("embed" => $embedID->embed_id); // } // break; // case "image": // foreach ($fieldValues as $fieldValue) { // try { // $fileID = PodioFile::copy($fieldValue->file_id); // } catch (Exception $e) { // Log::error("No rights to add prev file"); // } // if (isset($fileID)) // $podioAttributes[$field->external_id][] = array("value" => $fileID->file_id); // } // break; // case "category": // foreach ($fieldValues as $fieldValue) { // $podioAttributes[$field->external_id][] = $fieldValue['id']; // } // break; // case "calculation": // case "app": // break; // case "money": // $podioAttributes[$field->external_id][] = array("currency" => $fieldValues['currency'], "value" => $fieldValues['value']); // break; // default: // $podioAttributes[$field->external_id] = $fieldValues ; // break; // } // } // if (!$newItemId) { // try{ // $response = PodioItem::create($newAppId,array('fields' => $podioAttributes, 'external_id' => $externalId),$options = array()); // $newItemId = $response->item_id; // if ($newItemId) // Log::info('New item created with itemId : ' . $newItemId); // }catch(Exception $e){ // Log::info('Exception: ' . $e); // } // } else { // try{ // $update = PodioItem::update($newItemId, array('fields' => $podioAttributes)); // if ($update) // Log::info('Item updated'); // }catch(Exception $e){ // Log::info('Exception: ' . $e); // Log::info($podioAttributes); // } // } // } // if(isset($newItemId)){ // Log::info("new item id : ".$newItemId); // $itemArray['item_id'] = $newItemId; // $appRepo = new AppToAppItemRepo(); // /** copy task start */ // Log::info("-------copy task-------"); // $itemArray['shareItem'] = 'true'; // $appRepo->copyTasks($itemArray,false,false,null,true); // /** copy task end */ // /** copy comments start */ // Log::info("----copy comments--------"); // $itemArray['item_created_by_comment'] = "*Item created by [" . $itemData->created_by->name . '](' . $itemData->created_by->url . ') on ' // . date('Y-m-d H:i:s', $itemData->created_on->getTimestamp()) . '(UTC)*' . PHP_EOL; // $appRepo->copyComments($itemArray,false,null,true); // /** copy comments end */ // /** copy files start */ // Log::info("----------copy files----------"); // $this->copyFiles($itemArray); // /** copy files end */ // } // } // $limit_count = $limit_count+1; // } // Log::info("End Process"); // dd("End Process"); // } } } else { dd("no user exist"); } } catch (Exception $e) { Log::error("getCopyMissingItemCheck Exception : " . $e); } } public function formatDate_1($value, $userID) { $user = $this->user->findOne(array('_id' => $userID)); $UTC = new DateTimeZone("UTC"); $newTZ = new DateTimeZone($user['timezone']); $date = new DateTime($value, $UTC); $date->setTimezone($newTZ); return $date->format('Y-m-d'); } public function formatTime_1($value, $userID) { $user = $this->user->findOne(array('_id' => $userID)); $UTC = new DateTimeZone("UTC"); $newTZ = new DateTimeZone($user['timezone']); $date = new DateTime($value, $UTC); $date->setTimezone($newTZ); return $date->format('H:i:s'); } public function getConnection() // https://podiocopy.phases.dk/test/connection { try { $dbs = []; $this->host = Config::get('database.connections.mongodb.host'); $this->port = Config::get('database.connections.mongodb.port'); $this->database = Config::get('database.connections.mongodb.database'); $this->username = Config::get('database.connections.mongodb.username'); $this->password = Config::get('database.connections.mongodb.password'); try { $uri = "mongodb://podiocopyuser:v3QyN%26l%5E%23BA33o@localhost:27017/podio_data_transfer"; $client = new MongoDB\Client($uri); $database = $client->selectDatabase('podio_data_transfer'); $collection = $client->selectCollection('users'); $result = $collection->findOne([ 'email' => 'jack@tekmar.co.uk' ]); // Output the result echo '<pre>'; print_r($result); echo "Connected to MongoDB successfully"; } catch (MongoDB\Driver\Exception\AuthenticationException $e) { echo "MongoDB Authentication Error: " . $e->getMessage(); } catch (MongoDB\Driver\Exception\ConnectionException $e) { echo "MongoDB Connection Error: " . $e->getMessage(); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } } catch (Exception $e) { dd($e); } } public function getQueueDetails() { //$appsModel->find(array('queue_id' => (String)$transfer['_id'])); try { $queue = $this->podioAppsModel->find(array('queue_id' => "65a8e48bf4fcbd94150efee2")); dd(count($queue->toArray())); } catch (Exception $e) { dd($e); } } }
Edit
Download
Unzip
Chmod
Delete