Save log data

@param Registry &$syncdata     the actual syncdata

@return string nothing
354606
public static function execute(&$syncdata)
	{
		self::init();
		try {
			$action = $syncdata->get('action');
			$completed = $syncdata->get('completed');
			if (empty($completed)) {
				$master = $syncdata->get('master');
				$syncid = $syncdata->get('syncid');
				$userbatch = $syncdata->get('userbatch', 500);

				//setup some variables
				$MasterPlugin = Factory::getAdmin($master);
				$MasterUser = Factory::getUser($master);

				$db = Factory::getDBO();
				if (!static::getStatus($syncid)) {
					//tell JFusion a sync is in progress
					static::changeStatus($syncid, 1);
					$user_count = 1;
					//going to die every x users so that apache doesn't time out
					//we should start with the import of slave users into the master

					/**
					 * should be reset at end.
					 */
					$slave_data = $syncdata->get('slave_data', array());
					$plugin_offset = $syncdata->get('plugin_offset', 0);
					if (!empty($slave_data)) {
						for ($i = $plugin_offset; $i < count($slave_data); $i++) {
							$syncdata->set('plugin_offset', $i);

							$user_offset = $syncdata->get('user_offset', 0);
							//get a list of users
							$jname = $slave_data[$i]->jname;
							if ($jname) {
								$SlavePlugin = Factory::getAdmin($jname);
								$SlaveUser = Factory::getUser($jname);
								if ($action == 'master') {
									$userlist = $SlavePlugin->getUserList($user_offset, $userbatch);
									$action_name = $jname;
									$action_reverse_name = $master;
								} else {
									$userlist = $MasterPlugin->getUserList($user_offset, $userbatch);
									$action_name = $master;
									$action_reverse_name = $jname;
								}

								//catch to determine if the plugin supports limiting users for sync performance
								if (count($userlist) != $slave_data[$i]->total_to_sync) {
									//the userlist has already been limited so just start with the first one from the retrieved results
									$user_offset = 0;
								}
								//perform the actual sync
								for ($j = $user_offset; $j < count($userlist); $j++) {
									$syncdata->set('user_offset', $syncdata->get('user_offset', 0) + 1);

									$status = array();
									$userinfo = new Userinfo(null);
									$userinfo->bind($userlist[$j]);

									$UpdateUserInfo = null;
									try {
										if ($action == 'master') {
											$userinfo = $SlaveUser->getUser($userinfo);
											if ($userinfo instanceof Userinfo) {
												$MasterUser->resetDebugger();
												if ($MasterUser->validateUser($userinfo)) {
													$UpdateUserInfo = $MasterUser->updateUser($userinfo);

													$status = $MasterUser->debugger->get();

													if (!$UpdateUserInfo instanceof Userinfo) {
														//make sure the userinfo is available
														$UpdateUserInfo = $MasterUser->getUser($userinfo);
													}
												}
											}
										} else {
											$userinfo = $MasterUser->getUser($userinfo);
											if ($userinfo instanceof Userinfo) {
												$SlaveUser->resetDebugger();
												if ($MasterUser->validateUser($userinfo)) {
													$UpdateUserInfo = $SlaveUser->updateUser($userinfo);

													$status = $SlaveUser->debugger->get();

													if (!$UpdateUserInfo instanceof Userinfo) {
														//make sure the userinfo is available
														$UpdateUserInfo = $SlaveUser->getUser($userinfo);
													}
												}
											}
										}
									} catch (Exception $e) {
										$status[LogLevel::ERROR] = $e->getMessage();
										$UpdateUserInfo = null;
									}

									$sync_log = new stdClass;
									$sync_log->syncid = $syncid;
									$sync_log->jname = $jname;
									$sync_log->message = '';
									$sync_log->data = '';

									$sync_log->username = $userlist[$j]->username;
									$sync_log->email = $userlist[$j]->email;

									if (!isset($status['action'])) {
										$status['action'] = 'error';
									}
									if (!$userinfo instanceof Userinfo || !$UpdateUserInfo instanceof Userinfo || !empty($status[LogLevel::ERROR])) {
										$status['action'] = 'error';
										$sync_log->message = (is_array($status[LogLevel::ERROR])) ? implode('; ', $status[LogLevel::ERROR]) : $status[LogLevel::ERROR];
										$error = new stdClass();
										$error->conflict = new stdClass();
										$error->conflict->userinfo = $UpdateUserInfo;
										$error->conflict->error = $status[LogLevel::ERROR];
										$error->conflict->debug = (!empty($status[LogLevel::DEBUG])) ? $status[LogLevel::DEBUG] : '';
										$error->conflict->jname = $action_reverse_name;
										$error->user = new stdClass();
										$error->user->jname = $action_name;
										$error->user->userinfo = $userinfo;
										$error->user->userlist = $userlist[$j];

										$sync_log->type = 'ERROR';
										if (!empty($error->conflict->userinfo->username) && ($error->user->userinfo->username != $error->conflict->userinfo->username)) {
											$sync_log->type = 'USERNAME';
										} else if (!empty($error->conflict->userinfo->email) && $error->user->userinfo->email != $error->conflict->userinfo->email) {
											$sync_log->type = 'EMAIL';
										}

										$sync_log->data = json_encode($error);
										$syncdata->set('sync_errors', $syncdata->get('sync_errors', 0) + 1);
									} else {
										//usersync loggin enabled
										$sync_log->username = isset($UpdateUserInfo->username) ? $UpdateUserInfo->username : $userinfo->username;
										$sync_log->email = isset($UpdateUserInfo->email) ? $UpdateUserInfo->email : $userinfo->email;
										if ($UpdateUserInfo instanceof Userinfo) {
											//update the lookup table
											if ($action == 'master') {
												$MasterUser->updateLookup($UpdateUserInfo, $userinfo);
											} else {
												$SlaveUser->updateLookup($userinfo, $UpdateUserInfo);
											}
										}
									}
									$sync_log->action = $status['action'];

									//append the error to the log
									$db->insertObject('#__jfusion_sync_details', $sync_log);

									//update the counters
									$slave_data[$i]->{$status['action']} += 1;
									$slave_data[$i]->total -= 1;

									$syncdata->set('slave_data', $slave_data);

									$syncdata->set('synced_users', $syncdata->get('synced_users', 0) + 1);
									//update the database, only store syncdata every 20 users for better performance
									if ($user_count >= 20) {
										if ($slave_data[$i]->total == 0) {
											//will force the next plugin and first user of that plugin on resume
											$syncdata->set('plugin_offset', $syncdata->get('plugin_offset', 0) + 1);
											$syncdata->set('user_offset', 0);
										}
										static::updateData($syncdata);
										//update counters
										$user_count = 1;
									} else {
										//update counters
										$user_count++;
									}
									$userbatch--;

									if ($syncdata->get('synced_users', 0) == $syncdata->get('total_to_sync', 0)) {
										break;
									} elseif ($userbatch == 0 || $slave_data[$i]->total == 0) {
										//exit the process to prevent an apache timeout; it will resume on the next ajax call
										//save the syncdata before exiting
										if ($slave_data[$i]->total == 0) {
											//will force  the next plugin and first user of that plugin on resume
											$syncdata->set('plugin_offset', $syncdata->get('plugin_offset', 0) + 1);
											$syncdata->set('user_offset', 0);
										}
										static::updateData($syncdata);
										//tell Joomla the batch has completed
										static::changeStatus($syncid, 0);
										return;
									}
								}
							}
						}
					}

					$syncdata->set('slave_data', $slave_data);
					if ($syncdata->get('synced_users', 0) == $syncdata->get('total_to_sync', 0)) {
						//end of sync, save the final data

						$syncdata->set('completed', true);
						static::updateData($syncdata);

						//update the finish time
						$db = Factory::getDBO();

						$query = $db->getQuery(true)
							->update('#__jfusion_sync')
							->set('time_end = ' . $db->quote(time()))
							->where('syncid = ' . $db->quote($syncid));

						$db->setQuery($query);
						$db->execute();
					}
					static::updateData($syncdata);
					static::changeStatus($syncid, 0);
				}
			}
		} catch (Exception $e) {
			Framework::raise(LogLevel::ERROR, $e);
		}
	}
624988
public function save($data = null)
    {
        if ($data !== null) {
            $this->data = $data;
        }

        return $this->getHandler()->renderPath($this->getPath(), $this->data);
    }
579153
public static function countLogData($syncid, $type = 'all')
	{
		$db = Factory::getDBO();

		$query = $db->getQuery(true)
			->select('COUNT(*)')
			->from('#__jfusion_sync_details')
			->where('syncid = ' . $db->quote($syncid));

		if ($type != 'all') {
			$query->where('action = ' . $db->quote($type));
		}
		$db->setQuery($query);
		return (int)$db->loadResult();
	}
462540
public function getData($key, $registry = null)
	{
		if ($registry == null) {
			$registry = $this->default;
		}
		if (is_string($key . $registry) && $this->registryExists($registry)) {
			if (array_key_exists($key, $this->data[self::REGISTRY][$registry])) {
				return $this->data[self::REGISTRY][$registry][$key];
			}
		}
		return null;
	}
1214922
public function save($model, $sync = false)
    {
        if (!$model instanceof $this->class) {
            throw new \RuntimeException(sprintf('Manager "%s" is unable to save model "%s"', get_class($this), get_class($model)));
        }

        $this->manager->persist($model);

        if ($sync) {
            $this->manager->flush();
        }
    }
767764
public function write_setting($data) {
        global $CFG;
        // do not change active CFG setting!
        $current = $CFG->{$this->name};
        $result = parent::write_setting($data);
        $CFG->{$this->name} = $current;
        return $result;
    }
1256409
protected function saveDotEnvData( $data )
	{
		$dotEnvPath = base_path( '.env' );
		$dotEnv = "\n";
		foreach( $data as $key => $value ) {
			$dotEnv .= "{$key}={$value}\n";
		}
		file_put_contents( $dotEnvPath, $dotEnv );
	}
659330
private function logAddressData($addressData) {
        $this->bugsnag->registerCallback(function ($report) use ($addressData) {
            $report->setMetaData([
                'ADDRESS_DATA' => $addressData
            ]);
        });
    }
683161
public function save(array $data = []) : bool
    {
        $this->fill($data);
        $result = null;

        if ($this->exists()) {
            $result = $this->update();
        } else {
            $result = $this->insert();
        }

        return $result->count() > 0;
    }
1244293
public function _saveDummyData( string $dummyData_file = null )
	{
		file_put_contents($dummyData_file ?: $this->_getDummyDataFileName(), serialize([
			'headers'  => $this->result_headers,
			'response' => $this->result_data_raw,
			'code'     => $this->result_code,
		]));
	}
559758
public function log($logData)
    {
        $handle = fopen($this->getLogFilePath(), "a+");
        if ($handle !== false) {
            if (is_string($logData)) {
                parse_str($logData, $result);
            } else {
                $result = $logData;
            }

            if (is_array($result)) {
                foreach ($result as $key => $value) {
                    if (is_string($value)) {
                        $result[$key] = urldecode($value);
                    }
                }
            }

            fwrite($handle, "======================= " . $this->getTitle() . " [" . date("Y-m-d H:i:s") . "] ======================= #\n\n");
            fwrite($handle, "SESS ID: " . $this->getLoggerSessionId() . "\n");
            fwrite($handle, trim(var_export($result, true)) . "\n\n");
            fclose($handle);
        }

        //resetting log title
        $this->setTitle('');
    }
162546
File syncLog(long stamp, final long startTxId, final URL url, String name, File tmpFile)
      throws IOException {
    final File[] localPaths = new File[] { tmpFile };

    // TODO add security if needed.
    LOG.info("Synchronizing log " + name + " from " + url);
    boolean success = false;
    try {
      TransferFsImage.doGetUrl(
          url,
          ImageSet.convertFilesToStreams(localPaths, journalStorage,
              url.toString()), journalStorage, true);
      assert tmpFile.exists();
      success = true;
    } finally {
      if (!success) {
        if (!tmpFile.delete()) {
          LOG.warn("Failed to delete temporary file " + tmpFile);
        }
      }
    }
    return tmpFile;
  }
374196
public function write(string $sessionId, string $sessionData)
    {
        return $this->getObject(\PG\MSF\Coroutine\File::class)->goWriteFile(
            "{$this->savePath}/{$this->sessionName}_{$sessionId}",
            $sessionData
        );
    }
1185095
public function save($key, $data, \DateTimeInterface $updatedAt = null)
    {
        $keyGen = $this->generateKey($key);
        $path = $this->putFile($keyGen, $data);
        $this->cache->save($keyGen, $updatedAt);
        return $path;
    }
1049351
public function syncNodeData($node_name, $datas, $type)
    {
        $datas = array_values($datas);
        ProcessManager::getInstance()->getRpcCall(ClusterProcess::class, true)->th_syncData($node_name, $datas, $type);
    }
44412
public function _flush($data)
    {
        $id = array_pop($this->_idStack);
        if ($id === null) {
            Zend_Cache::throwException('use of _flush() without a start()');
        }
        if ($this->_extension) {
            $this->save(serialize(array($data, $this->_extension)), $id, $this->_tags);
        } else {
            $this->save($data, $id, $this->_tags);
        }
        return $data;
    }
1038732
protected function encodeData($serializedData)
    {
        $result = json_encode($serializedData);
        if ($result === false) {
            $errorCode = json_last_error();
            throw new JsonException("Failed serialize json.", $errorCode);
        }

        return $result;
    }