Create a new pivot attachment record.

@param  int   $id
@param  bool  $timed
@return array
197941
protected function baseAttachRecord($id, $timed)
    {
        return array_set(parent::baseAttachRecord($id, $timed), $this->morphType, $this->morphClass);
    }
204531
public function exportById($id): array
    {
        $entryType = Craft::$app->sections->getEntryTypeById((int) $id);

        return $this->export($entryType);
    }
1080283
public function update(Request $request, $id)
    {
        // Handle permission
//        $request = $this->handlePermission(__FUNCTION__,$request);
//        if ($request->has('permission_filters')){
//            $filters = $request['permission_filters'];
//        }else{
        $filters = [];
//        }

        // Create Response Model
        $response = new ResponseModel();

        // Filters
        array_push($filters,
            [$this->model->getKeyName(), '=', $id]
        );

        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
        if ($validationErrors != null) {
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($validationErrors->toArray()));
            }
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
            $response->setStatus(false);
            $response->setError(99);
            return SmartResponse::response($response);

        }

        try {
            // sync many to many relation
            foreach ($this->pivotFields as $pivotField) {
                if (collect($request[$pivotField])->count()) {
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
                }
            }
            //get result of update
            $result = $this->model->where($filters)->firstOrFail()->update($request->all());

            // return response
            $response->setData($this->model
                ->where($filters)
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
                ->get());
            $response->setMessage(
                $this->getTrans(__FUNCTION__, 'successful1') .
                $result .
                $this->getTrans(__FUNCTION__, 'successful2')
            );

        } catch (ModelNotFoundException $exception) {
            $response->setStatus(false);
            $response->setMessage($this->getTrans(__FUNCTION__, 'model_not_found'));
            $response->setError($exception->getCode());
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($exception->getMessage()));
            }

        } catch (QueryException $exception) {
            $response->setStatus(false);
            $response->setMessage($this->getTrans(__FUNCTION__, 'failed'));
            $response->setError($exception->getCode());
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($exception->getMessage()));
            }

        }

        return SmartResponse::response($response);
    }
133964
protected function createAttachRecord($id, $timed)
	{
		$record[$this->foreignKey] = $this->parent->getKey();

		$record[$this->otherKey] = $id;

		// If the record needs to have creation and update timestamps, we will make
		// them by calling the parent model's "freshTimestamp" method which will
		// provide us with a fresh timestamp in this model's preferred format.
		if ($timed)
		{
			$record = $this->setTimestampsOnAttach($record);
		}

		return $record;
	}
1242081
public function fileAction($id, $type)
    {
        $cm = new CronManager();
        $crons = $cm->get();
        $cron = $crons[$id];

        $data = array();
        $data['file'] =  ($type == 'log') ? $cron->getLogFile(): $cron->getErrorFile();
        $data['content'] = \file_get_contents($data['file']);

        $serializer = new Serializer(array(), array('json' => new JsonEncoder()));

        return new Response($serializer->serialize($data, 'json'));
    }
1264468
public function attachFiles($id, $table, $files)
    {
        foreach ($files as $file) {
            if (!empty($file)) {
                $this->attachFile($id, $table, $file);
            }
        }
    }
644274
public static function setTimeout($id, $timeout = null)
    {
        if (isset(self::$list[$id])) {
            self::$list[$id]->timeout($timeout);
            return true;
        }
        return false;
    }
739252
public function withTimestamps($createdAt = null, $updatedAt = null)
    {
        $this->pivotCreatedAt = $createdAt;
        $this->pivotUpdatedAt = $updatedAt;

        return $this->withPivot($this->createdAt(), $this->updatedAt());
    }
492018
protected function baseAttachRecord($id, $timed)
    {
        return Arr::add(
            parent::baseAttachRecord($id, $timed), $this->morphType, $this->morphClass
        );
    }
1088972
public function exportById($id): array
    {
        $transform = Craft::$app->assetTransforms->getTransformById((int) $id);

        return $this->export($transform);
    }
183478
public function attachFile($id, $table, \Symfony\Component\HttpFoundation\File\UploadedFile $file)
    {
        $newFileName = md5(microtime() . '.' . strtolower($file->getClientOriginalExtension()));
        $relativePath = $table . '/' . date('Y/m/d');
        $relativeFilePath = $relativePath . '/' . $newFileName;
        $dstPath = APP_UPLOADS_DIR . '/' . $relativePath;
        $file->move($dstPath, $newFileName);
        $pic = new \Towel\Model\Pic();

        $pic->object_id = $id;
        $pic->object_type = $table;
        $pic->pic = $relativeFilePath;
        $pic->created = time();
        $pic->save();
    }
1051270
public function deleteAttachment($id) {
		if(!StorageSettings::deleteFromStorage()) {
			return $id;
		}

		$data = wp_get_attachment_metadata($id);
		if(isset($data['file']) && !isset($data['s3'])) {
			return $id;
		}

		if($this->client && $this->client->enabled()) {
			if(!isset($data['file'])) {
				$file = get_attached_file($id);
				if($file) {
					if(strpos($file, 'http') === 0) {
						$pi = parse_url($file);
						$file = trim($pi['path'], '/');
						if(0 === strpos($file, $this->client->bucket())) {
							$file = substr($file, strlen($this->client->bucket())).'';
							$file = trim($file, '/');
						}
					} else {
						$pi = pathinfo($file);
						$upload_info = wp_upload_dir();
						$upload_path = $upload_info['basedir'];

						$file = trim(str_replace($upload_path, '', $pi['dirname']), '/').'/'.$pi['basename'];
					}

					$this->deleteFile($file);
				}
			} else {
			    $deletedFiles = [];

			    $deletedFiles[] = $data['s3']['key'];
				$this->deleteFile($data['s3']['key']);

				if(isset($data['sizes'])) {
					$pathParts = explode('/', $data['s3']['key']);
					array_pop($pathParts);
					$path_base = implode('/', $pathParts);

					foreach($data['sizes'] as $key => $size) {
						$file = arrayPath($size,'s3/key', false);
						if (!$file) {
						    $file = $path_base.'/'.$size['file'];
                        }

                        if (in_array($file, $deletedFiles)) {
					        Logger::info("File '$file' has already been deleted.");
					        continue;
                        }

                        $this->deleteFile($file);

						$deletedFiles[] = $file;
					}
				}
			}
		}

		return $id;
	}
773954
protected function addTimestampsToAttachment(array $record, $exists = false)
    {
        $fresh = $this->parent->freshTimestamp();

        if ($this->using) {
            $pivotModel = new $this->using;

            $fresh = $fresh->format($pivotModel->getDateFormat());
        }

        if (! $exists && $this->hasPivotColumn($this->createdAt())) {
            $record[$this->createdAt()] = $fresh;
        }

        if ($this->hasPivotColumn($this->updatedAt())) {
            $record[$this->updatedAt()] = $fresh;
        }

        return $record;
    }
255600
public function getAggregateHistoryFor(Identity $id, $offset = 0, $max = null)
    {
        $stream = fopen($this->dataPath . '/' . (string) $id, 'r');

        $events = [];

        $i = 0;

        while (!feof($stream)) {
            if (!is_null($max) && $i > $max) {
                break;
            }

            if ($i < $offset) {
                continue;
            }

            $events[] = unserialize(fgets($stream));
            ++$i;
        }

        fclose($stream);

        return new CommittedEvents($id, $events);
    }
868632
public static function duplicate_template($id) {
        global $PAGE;

        $params = self::validate_parameters(self::duplicate_template_parameters(), array('id' => $id));

        $template = api::read_template($params['id']);
        self::validate_context($template->get_context());
        $output = $PAGE->get_renderer('core');

        $result = api::duplicate_template($params['id']);
        $exporter = new template_exporter($result);
        return $exporter->export($output);
    }
909118
public function markSnapShot($id, $time = 1) {
		$snap_info = array(
			$id => array(
				// We use the same time values as in markSnapViewed, but add in the
				// screenshot status.
				't' => microtime(TRUE),
				'sv' => $time + (mt_rand() / mt_getrandmax() / 10),
				'c' => self::STATUS_SCREENSHOT,
			),
		);

		$events = array(
			array(
				'eventName' => 'SNAP_SCREENSHOT',
				'params' => array(
					'id' => $id,
				),
				'ts' => time() - $time,
			),
		);

		return $this->sendEvents($events, $snap_info);
	}
678818
public function exportById($id): array
    {
        $site = Craft::$app->sites->getSiteById((int) $id);

        return $this->export($site);
    }