<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/

class Activity_Api_Core extends Core_Api_Abstract 
{
    /**
   * Loader for parsers
   *
   * @var Zend_Loader_PluginLoader
   */
  protected $_pluginLoader;

  /**
   * Activity template parsing
   *
   * @param string $body
   * @param array $params
   * @return string
   */
  public function fetchAction($action_ids, $param = 0) {

    $table = Engine_Api::_()->getDbTable('actions','activity');
    $tableName = $table->info('name');
    $select = $table->select()->from($tableName,array("action_id","subject_type","subject_id"))->group("subject_id");
    if(empty($param)) {
      $select->where("action_id IN (".$action_ids.")");
    } else {
      $select->where("action_id IN (?)", $action_ids);
    }

    return ($table->fetchAll($select));
  }

  public function assemble($body, array $params = array(),$break = true,$group_feed = false)
  {
    $paramsArray = $params['params'];
    if(is_array($paramsArray) && engine_count($paramsArray)){
        if(!empty($paramsArray['owner']) && empty($params['owner'])){
           unset($params['owner']);
           $params =  array_merge(array('owner'=> Engine_Api::_()->getItemByGuid($paramsArray['owner'])),$params);
        }
    }
    // Translate body
    $body = $this->getHelper('translate')->direct($body);
    if (strpos($body, '{body:$body}') === false) {
      $body .= '{body:$body}';
    }
    $body =  $body.'|||||---|||++'.$break;
 
    preg_match_all('~\{([^{}]+)\}~', $body, $matches, PREG_SET_ORDER);

    foreach( $matches as $match )
    {
      $tag = $match[0];
      $args = explode(':', $match[1]);
      $helper = array_shift($args);

      $helperArgs = array();
      foreach( $args as $arg )
      {
        if( substr($arg, 0, 1) === '$' )
        {
          $valid = true;
          $arg = substr($arg, 1);
          if($arg == "subject" && !empty($params['resource_id']) && !empty($params['resource_type'])){
            $item = Engine_Api::_()->getItem($params['resource_type'],$params['resource_id']);
            if($item){
              $helperArgs[] =  $item;
              $valid = false;
            }
          }
          if($valid)
            $helperArgs[] = ( isset($params[$arg]) ? $params[$arg] : null );
        }
        else
        {
          $helperArgs[] = $arg;
        }
      }
      $helper = $this->getHelper($helper);
      $r = new ReflectionMethod($helper, 'direct');

      $content = $r->invokeArgs($helper, $helperArgs);
      $content = preg_replace('/\$(\d)/', '\\\\$\1', $content);
      $body = preg_replace("/" . preg_quote($tag) . "/", $content, $body, 1);
    }
    $body = str_replace('|||||---|||++'.$break,'',$body);
    if($break)
		  $body = explode('BODYSTRING',$body);
    else
      $body = str_replace('BODYSTRING','',$body);
    return $body;
  }
  
  /**
   * Gets the plugin loader
   *
   * @return Zend_Loader_PluginLoader
   */
  public function getPluginLoader()
  {
    if( null === $this->_pluginLoader )
    {
      $path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR
          . 'modules' . DIRECTORY_SEPARATOR
          . 'Activity';
      $this->_pluginLoader = new Zend_Loader_PluginLoader(array(
        'Activity_Model_Helper_' => $path . '/Model/Helper/'
      ));
    }

    return $this->_pluginLoader;
  }

  /**
   * Get a helper
   *
   * @param string $name
   * @return Activity_Model_Helper_Abstract
   */
  public function getHelper($name)
  {
    $name = $this->_normalizeHelperName($name);
    if( !isset($this->_helpers[$name]) )
    {
      $helper = $this->getPluginLoader()->load($name);
      $this->_helpers[$name] = new $helper;
    }

    return $this->_helpers[$name];
  }

  /**
   * Normalize helper name
   *
   * @param string $name
   * @return string
   */
  protected function _normalizeHelperName($name)
  {
    $name = preg_replace('/[^A-Za-z0-9]/', '', $name);
    //$name = strtolower($name);
    $name = ucfirst($name);
    return $name;
  }
  
  public function getNetworks($type, $viewer) {
    $ids = array();
    $viewer_id = $viewer->getIdentity();
    if (empty($type) || empty($viewer_id)) {
        return;
    }

    if( $type == 1 ) {
        $networkTable = Engine_Api::_()->getDbtable('membership', 'network');
        $ids = $networkTable->getMembershipsOfIds($viewer);
        $count = engine_count($ids);
        if( empty($count) ) {
            return;
        }

        $ids = array_unique($ids);
    }

    $table = Engine_Api::_()->getItemTable('network');
    $select = $table->select()
        ->order('title ASC');
    if ($type == 1 && !empty($ids)) {
        $select->where('network_id IN(?)', $ids);
    }
    return $table->fetchAll($select);
  }

  public function isNetworkBasePrivacy($string) {
    if (empty($string)) {
        return;
    }

    $arr = explode(',', $string);
    return preg_match("/network_/", $arr[0]);
  }

  public function getNetworkBasePrivacyIds($string) {
    if (empty($string)) {
        return;
    }

    $ids = array();
    $arr = explode(',', $string);
    foreach ($arr as $val) {
        $ids[] = str_replace('network_', '', $val);
    }
    return $ids;
  }

  public function getSpecialAlbum(User_Model_User $user, $type, $auth_view) {
  
    if (!engine_in_array($type, array('wall_friend', 'wall_network', 'wall_onlyme'))) {
      throw new Album_Model_Exception('Unknown special album type');
    }
    $table = Engine_Api::_()->getDbtable('albums', 'album');
    $select = $table->select()
      ->where('owner_type = ?', $user->getType())
      ->where('owner_id = ?', $user->getIdentity())
      ->where('type = ?', $type)
      ->order('album_id ASC')
      ->limit(1);

    $album = $table->fetchRow($select);

    // Create wall photos album if it doesn't exist yet
    if (null === $album) {
      $translate = Zend_Registry::get('Zend_Translate');
      $album = $table->createRow();
      $album->owner_type = 'user';
      $album->owner_id = $user->getIdentity();
      $album->title = $translate->_(ucfirst(str_replace("_", " ", $type)) . ' Photos');
      $album->type = $type;
      $album->save();

      // Authorizations
      $auth = Engine_Api::_()->authorization()->context;
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
      $viewMax = array_search($auth_view, $roles);
      foreach ($roles as $i => $role) {
          $auth->setAllowed($album, $role, 'view', ($i <= $viewMax));
          $auth->setAllowed($album, $role, 'comment', ($i <= $viewMax));
      }
    }

    return $album;
  }
  
  public function editContentPrivacy($item, $user, $auth_view = null) {
    $type = null;
    switch ($auth_view) {
        case 'everyone':
            $auth_view = "everyone";
            break;
        case 'networks':
            $auth_view = "owner_network";
            $type = '_network';
            break;
        case 'friends':
            $auth_view = 'owner_member';
            $type = '_friend';
            break;
        case 'onlyme':
            $auth_view = 'owner';
            $type = '_onlyme';
            break;
    }
    if (empty($auth_view)) {
        $auth_view = "everyone";
    }

    // Work For Album
    if ($item->getType() == 'album_photo') {
        $parent = $item->getParent();
        if ($auth_view != "everyone") {
            $type = 'wall' . $type;
            $album = $this->getSpecialAlbum($user, $type, $auth_view);
            if (isset($item->album_id)) {
                $item->album_id = $album->album_id;
            } else {
                $item->collection_id = $album->album_id;
            }

            $item->save();
        }
    }


    // Work For Music
    if ($item->getType() == 'music_playlist_song') {
        $parent = $item->getParent();
        if ($auth_view != "everyone") {
            $type = 'wall' . $type;
            $playlist = $this->getSpecialPlaylist($user, $type, $auth_view);
            $item->playlist_id = $playlist->playlist_id;
            $item->save();
        }
    }

    $auth = Engine_Api::_()->authorization()->context;
    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
    $viewMax = array_search($auth_view, $roles);
    foreach ($roles as $i => $role) {
        $auth->setAllowed($item, $role, 'view', ($i <= $viewMax));
    }
  }
  
  public function getSpecialPlaylist(User_Model_User $user, $type, $auth_view)
  {
    if (!engine_in_array($type, array('wall_friend', 'wall_network', 'wall_onlyme'))) {
      throw new Music_Model_Exception('Unknown special album type');
    }
    
    $table = Engine_Api::_()->getDbtable('playlists', 'music');
    $select = $table->select()
        ->where('owner_type = ?', $user->getType())
        ->where('owner_id = ?', $user->getIdentity())
        ->where('special = ?', $type)
        ->order('playlist_id ASC')
        ->limit(1);

    $playlist = $table->fetchRow($select);

    // Create if it doesn't exist yet
    if( null === $playlist ) {
      $translate = Zend_Registry::get('Zend_Translate');

      $playlist = $table->createRow();
      $playlist->owner_type = 'user';
      $playlist->owner_id = $user->getIdentity();
      $playlist->special = $type;

      if( $type == 'message' ) {
        $playlist->title = $translate->_('_MUSIC_MESSAGE_PLAYLIST');
        $playlist->search = 0;
      } else {
        $playlist->title = $translate->_('_MUSIC_DEFAULT_PLAYLIST');
        $playlist->search = 1;
      }
      //approve setting work
      $playlist->approved = Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('music_playlist', $user, 'approve');
      $playlist->save();

      // Authorizations
      $auth = Engine_Api::_()->authorization()->context;
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
      $viewMax = array_search($auth_view, $roles);
      foreach ($roles as $i => $role) {
          $auth->setAllowed($playlist, $role, 'view', ($i <= $viewMax));
          $auth->setAllowed($playlist, $role, 'comment', ($i <= $viewMax));
      }
    }

    return $playlist;
  }
  
  public function getHashTags($string) {
    preg_match_all("/\s(#[^\s[!\"\#$%&'()*+,\-.\/\\:;<=>?@\[\]\^`{|}~]+)/", ' ' . $string, $hashtags);
    if (!empty($hashtags[0])) {
        foreach ($hashtags[0] as $key => $hashtag) {
            $hashtag = str_replace('#', '', $hashtag);
            $hashtags[0][$key] = trim($hashtag);
        }
    }

    return $hashtags;
  }

  public function getEmoticons($withIcons = false, $tinyEditor = false, $chatEmotions = false)
  {
    $filePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR
        . 'modules' . DIRECTORY_SEPARATOR
        . "Activity/externals/emoticons/emoticons.php";
    $emoticons = file_exists($filePath) ? include $filePath : NULL;

    if (!$withIcons && !$tinyEditor && !$chatEmotions) {
        return $emoticons;
    }

    if($tinyEditor) {
        $emoticonString = '[';
        foreach($emoticons as $emoticon) {
            $emoticonString .= '"'.$emoticon.'",';
        }
        $emoticonString .= ']';
        return $emoticonString;
    }

    //Chat emoticon
    if($chatEmotions) {
        $emoticonArray = array();
        foreach($emoticons as $symbol => $emoticon) {
            $emoticonArray[$symbol] = $emoticon;
        }
        return json_encode($emoticonArray, JSON_HEX_QUOT | JSON_HEX_TAG);
    }

    $emoticonIcons = array();
    foreach ($emoticons as $symbol => $icon) {
      $emoticonIcons[" ".$symbol." "] = "<img class = \"emoticon_img\" src=\"" . Zend_Registry::get('Zend_View')->layout()->staticBaseUrl . "application/modules/Activity/externals/emoticons/images/$icon\" border=\"0\" />";
      $emoticonIcons[$symbol." "] = "<img class = \"emoticon_img\" src=\"" . Zend_Registry::get('Zend_View')->layout()->staticBaseUrl . "application/modules/Activity/externals/emoticons/images/$icon\" border=\"0\" />";
      $emoticonIcons[" ". $symbol] = "<img class = \"emoticon_img\" src=\"" . Zend_Registry::get('Zend_View')->layout()->staticBaseUrl . "application/modules/Activity/externals/emoticons/images/$icon\" border=\"0\" />";
    }
    return $emoticonIcons;
  }
  function convertEmojiIcon($string){
		$emojiIcon = "";
		foreach(explode('_',$string) as $icon){
			$emojiIcon .= "\u{$icon}";
		}
		return preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $emojiIcon);
	}

 
  public function uploadBackgrounds() {

    $backgroundTable = Engine_Api::_()->getDbtable('backgrounds', 'activity');
    
    $PathFile = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'Activity' . DIRECTORY_SEPARATOR . "externals" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "backgrounds" . DIRECTORY_SEPARATOR;

    $file_display = array('jpg', 'jpeg', 'png', 'gif');
    if (file_exists($PathFile)) {
      $dir_contents = scandir( $PathFile );
      foreach ( $dir_contents as $file ) {
        $explode = explode('.', @$file );
        $class = end( $explode );
        $file_type = strtolower($class);
        if ( ($file !== '.') && ($file !== '..') && (engine_in_array( $file_type, $file_display)) ) {
          $images = explode('.', $file);
          
          //$db = Engine_Db_Table::getDefaultAdapter();
          //$db->beginTransaction();
          // If we're here, we're done
          try {
            $item = $backgroundTable->createRow();
            $values['enabled'] = 1;
            $values['starttime'] = date('Y-m-d');
            $values['enableenddate'] = 1;

            $item->setFromArray($values);
            $item->save();
            $item->order = $item->background_id;
            $item->save();
            if(!empty($file)) {
              $file_ext = pathinfo($file);
              $file_ext = $file_ext['extension'];
              $storage = Engine_Api::_()->getItemTable('storage_file');
              $pngFile = $PathFile . $file;
              $storageObject = $storage->createFile($pngFile, array(
                'parent_id' => $item->background_id,
                'parent_type' => 'activity_background',
                'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
              ));
              // Remove temporary file
              ////@unlink($file['tmp_name']);
              $item->file_id = $storageObject->file_id;
              $item->save();
            }
            //$db->commit();
          } catch(Exception $e) {
            //$db->rollBack();
            //throw $e;
          }
        }
      }
    }
  }


  public function uploadFeelingsMainIconsActivity() {

    $paginator = Engine_Api::_()->getDbTable('feelings','activity')->getFeelings(array('fetchAll' => 1, 'admin' => 1));
    foreach($paginator as $item) {

      $feelings = explode(' ',strtolower($item->title));

      $foldername = '';
      if(@$feelings[0]) {
        $foldername .= @$feelings[0];
      }

      if(@$feelings[1]) {
        $foldername .= '_'.@$feelings[1];
      }

      //Main Feeling icon work
      $mainFeelingIcon = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'Activity' . DIRECTORY_SEPARATOR . "externals" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "feeling_activity" . DIRECTORY_SEPARATOR . 'feeling_activity_tittle_icons' . DIRECTORY_SEPARATOR . $foldername.'.png';

      if (file_exists($mainFeelingIcon)) {

        $file_ext = pathinfo($mainFeelingIcon);
        $file_ext = $file_ext['extension'];
        $storage = Engine_Api::_()->getItemTable('storage_file');
        $storageObject = $storage->createFile($mainFeelingIcon, array(
          'parent_id' => $item->feeling_id,
          'parent_type' => 'activity_feeling',
          'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
        ));

        // Remove temporary file
        //@unlink($file['tmp_name']);
        $item->file_id = $storageObject->file_id;
        $item->save();
      }
      //Main Feeling icon work
    }
  }

  public function uploadFeelingsActivity() {

    $feelingiconsTable = Engine_Api::_()->getDbtable('feelingicons', 'activity');

    $paginator = Engine_Api::_()->getDbTable('feelings','activity')->getFeelings(array('fetchAll' => 1, 'admin' => 1));
    foreach($paginator as $item) {

      $feelings = explode(' ',strtolower($item->title));
      $foldername = '';

      if(@$feelings[0]) {
        $foldername .= @$feelings[0];
      }

      if(@$feelings[1]) {
        $foldername .= '_'.@$feelings[1];
      }

      $PathFile = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'Activity' . DIRECTORY_SEPARATOR . "externals" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "feeling_activity" . DIRECTORY_SEPARATOR . $foldername . DIRECTORY_SEPARATOR;

      // Get all existing log files
      $logFiles = array();
      $file_display = array('jpg', 'jpeg', 'png', 'gif');
      if (file_exists($PathFile)) {

        $dir_contents = scandir( $PathFile );

        foreach ( $dir_contents as $file ) {

          $fileex = explode('.', $file );
          $fileend = end( $fileex );
          $file_type = strtolower( $fileend );
          if ( ($file !== '.') && ($file !== '..') && (engine_in_array( $file_type, $file_display)) ) {

            $images = explode('.', $file);
            //$db = Engine_Db_Table::getDefaultAdapter();
            //$db->beginTransaction();
            // If we're here, we're done

            try {

              $values['title'] = str_replace('_', ' ', $images[0]);
              $values['type'] = 1;
              $values['feeling_id'] = $item->feeling_id;

              $getEmojiIconExist = Engine_Api::_()->getDbTable('feelingicons', 'activity')->getFeelingIconExist(array('title' => str_replace('_', ' ', $images[0])));

              if(empty($getEmojiIconExist)) {

                $item = $feelingiconsTable->createRow();

                $item->setFromArray($values);
                $item->save();

                if(!empty($file)) {
                  $file_ext = pathinfo($file);
                  $file_ext = $file_ext['extension'];
                  $storage = Engine_Api::_()->getItemTable('storage_file');

                  $pngFile = $PathFile . $file;

                  $storageObject = $storage->createFile($pngFile, array(
                    'parent_id' => $item->getIdentity(),
                    'parent_type' => $item->getType(),
                    'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
                  ));

                  // Remove temporary file
                  ////@unlink($file['tmp_name']);
                  $item->feeling_icon = $storageObject->file_id;
                  $item->save();
                }
                //$db->commit();
              }
            } catch(Exception $e) {
              //$db->rollBack();
              //throw $e;
            }
          }
        }
      }
    }
  }

  public function uploadReactions() {

    $mangereaction = Engine_Api::_()->getApi('settings', 'core')->getSetting('comment.managereactions', 0);
    if(empty($mangereaction)) {

      //Upload Reactions
      $reactionsTable = Engine_Api::_()->getDbTable('reactions', 'comment');
      $emotiongalleriesselect = $reactionsTable->select()->order('reaction_id ASC');
      $paginator = $reactionsTable->fetchAll($emotiongalleriesselect);
      $db = Engine_Db_Table::getDefaultAdapter();

      if(engine_count($paginator) > 0) {
        foreach($paginator as $result) {

          $title = $result->title;
          if($title == 'Like') {
            $title = 'icon-like';
          } elseif($title == 'Love') {
            $title = 'icon-love';
          } elseif($title == 'Sad') {
            $title = 'icon-sad';
          } elseif($title == 'Wow') {
            $title = 'icon-wow';
          } elseif($title == 'Haha') {
            $title = 'icon-haha';
          } elseif($title == 'Angry') {
            $title = 'icon-angery';
          }

          $PathFile = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'Comment' . DIRECTORY_SEPARATOR . "externals" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR;

          if (is_file($PathFile . $title . '.png'))  {
            $pngFile = $PathFile . $title . '.png';
            $photo_params = array(
                'parent_id' => $result->reaction_id,
                'parent_type' => "comment_reaction",
            );
            $photoFile = Engine_Api::_()->storage()->create($pngFile, $photo_params);
            if (!empty($photoFile->file_id)) {
              $db->update('engine4_comment_reactions', array('file_id' => $photoFile->file_id), array('reaction_id = ?' => $result->reaction_id));
            }
          }
        }
        Engine_Api::_()->getApi('settings', 'core')->setSetting('comment.managereactions', 1);
      }
    }
  }

  public function previewHTML($uri) {
    // clean URL for html code
    $uri = trim(strip_tags($uri));
    $info = parse_url($uri);
    $this->_linkDetail['url'] = $uri;

		try {
			if (!Engine_Api::_()->getApi('security', 'core')->isValidExternalUrl($uri)) {
				$this->_linkDetail['error'] = 'Invalid URL provided.';
				return $this->_linkDetail;
			}
		} catch( Exception $e ) { 
			throw $e;
		}

    try {
      $config = Engine_Api::_()->getApi('settings', 'core')->core_iframely;
      if( !empty($config['host']) && $config['host'] != 'none' ) {
        $this->_getFromIframely($config, $uri);
        $this->_linkDetail['title'] = Engine_String::convertUtf8($this->_linkDetail['title']);
        $this->_linkDetail['description'] = Engine_String::convertUtf8($this->_linkDetail['description']);
        return $this->_linkDetail;
      }
    } catch( Exception $e ) {}

		try
		{
			$client = new Zend_Http_Client($uri, array(
				'maxredirects' => 0,
				'timeout'      => 20,
			));

			// Try to mimic the requesting user's UA
			$client->setHeaders(array(
				'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
				'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
				'X-Powered-By' => 'Zend Framework'
			));

			$response = $client->request();
			// Get DOM


			$this->_linkDetail['isGif'] = false;
			$this->_linkDetail['isIframe'] = false;
			$body = $response->getBody();
			$body = trim($body);
			if( preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getHeader('content-type'), $matches) ||
					preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getBody(), $matches) ) {
				$this->_linkDetail['charset'] = $charset = trim($matches[1]);
			} else {
				$this->_linkDetail['charset'] = $charset = 'UTF-8';
			}
			if( function_exists('mb_convert_encoding') ) {
				$body = mb_convert_encoding($body, 'HTML-ENTITIES', $charset);
			}
			if( class_exists('DOMDocument') ) {
				$dom = new Zend_Dom_Query($body);
			} else {
				$dom = null; // Maybe add b/c later
			}

			if($dom && $gifImage = $dom->queryXpath("//meta[@property='og:url']")){
				if($gifImage->current() && strpos($gifImage->current()->getAttribute('content'),'.gif') !== false){
				$this->_linkDetail['isGif'] = true;
				$gifImageUrl = $dom->queryXpath("//meta[@property='og:image']");
				if(strpos($gifImageUrl->current()->getAttribute('content'),'.jpg') !== false)
					$image = $gifImageUrl->current()->getAttribute('content');
				else{
					$image = $gifImageUrl->current()->getAttribute('content');
				}
				
				$this->_linkDetail['gifImageUrl'] = $image;
				$this->_linkDetail['gifUrl'] = $gifImage->current()->getAttribute('content');
				$this->_linkDetail['title'] = '';
				$this->_linkDetail['description'] = '';
				$this->_linkDetail['images'] = array();
				$this->_linkDetail['imageCount'] = 0;
				}
			}
			$uploadedFile = '';
			if(strpos($uri, '.gif') !== false){
				$tmp_path = APPLICATION_PATH . '/temporary/link';

				if( !is_dir($tmp_path) && !mkdir($tmp_path, 0777, true) ) {
					throw new Sesadvancedactivity_Model_Exception('Unable to create tmp link folder : ' . $tmp_path);
				}
				$imgPath = $tmp_path.time().'.gif';
				$contentImage = imagepng(imagecreatefromstring(file_get_contents($uri)), $imgPath);;
				//$contentImage = file_put_contents($imgPath, file_get_contents($uri));
				$thumbnail = (string) @$imgPath;
				$thumbnail_parsed = @parse_url($thumbnail);

				$tmp_file = $tmp_path . '/' . md5($thumbnail);

				$src_fh = fopen($thumbnail, 'r');
				$tmp_fh = fopen($tmp_file, 'w');
				stream_copy_to_stream($src_fh, $tmp_fh, 1024 * 1024 * 2);
				fclose($src_fh);
				fclose($tmp_fh);
				if( ($info = getimagesize($tmp_file)) && !empty($info[2]) ) {
					$ext = Engine_Image::image_type_to_extension($info[2]);
					$thumb_file = $tmp_path . '/thumb_'.md5($thumbnail) . '.'.$ext;

					$image = Engine_Image::factory();
					$image->open($tmp_file)
						->autoRotate()
						->resize(500, 500)
						->write($thumb_file)
						->destroy();

					$thumbFileRow = Engine_Api::_()->storage()->create($thumb_file, array(
						'parent_type' => 'core_link',
						'parent_id' => '999999999999999'
					));
					$uploadedFile = $thumbFileRow->map();
					@unlink($thumb_file);
					@unlink($imgPath);
				}
				$this->_linkDetail['isGif'] = true;
				$this->_linkDetail['gifImageUrl'] = $uploadedFile;
				$this->_linkDetail['gifUrl'] = $uri;
				$this->_linkDetail['title'] = '';
				$this->_linkDetail['description'] = '';
				$this->_linkDetail['images'] = array();
				$this->_linkDetail['imageCount'] = 0;
			}else if(strpos($uri,'youtubevideo') !== false || strpos($uri,'vimeovideo') !== false || strpos($uri,'soundcloud') !== false || strpos($uri,'https://youtu.be/') !== false){

				$title = null;
				if( $dom ) {
					$titleList = $dom->query('title');
					if( engine_count($titleList) > 0 ) {
						$title = trim($titleList->current()->textContent);
						$title = substr($title, 0, 255);
					}
				}
				$this->_linkDetail['title'] = $title;

				$description = null;
				if( $dom ) {
					$descriptionList = $dom->queryXpath("//meta[@name='description']");
					// Why are they using caps? -_-
					if( engine_count($descriptionList) == 0 ) {
						$descriptionList = $dom->queryXpath("//meta[@name='Description']");
					}
					// Try to get description which is set under og tag
					if( engine_count($descriptionList) == 0 ) {
						$descriptionList = $dom->queryXpath("//meta[@property='og:description']");
					}
					if( engine_count($descriptionList) > 0 ) {
						$description = trim($descriptionList->current()->getAttribute('content'));
						$description = substr($description, 0, 255);
					}
				}
				$this->_linkDetail['description'] = $description;
				$this->_linkDetail['isGif'] = false;
				$this->_linkDetail['gifUrl'] = '';
				$parseUrl = parse_url($uri);
				$url = parse_str($parseUrl['query'],$array);
				if(strpos($uri,'https://youtu.be') !== false){
					$array['v'] = end(explode('/',$uri));
					$uri = 'youtubevideo';
				}


				if(strpos($uri,'youtubevideo') !== false ){
					$this->_linkDetail['thumb'] = '<iframe width="100%" height="320" src="https://www.youtube.com/embed/'.$array["v"].'?'.(!empty($array['list']) ? 'list='.$array['list'] : '').'" frameborder="0" allowfullscreen></iframe>';
				}
				else if(strpos($uri,'soundcloud') !== false ){
					$this->_linkDetail['thumb'] = '<iframe frameborder="no" width="100%" height="400" src="https://w.soundcloud.com/player/?visual=true&url='.$uri.'&show_artwork=true" scrolling="no"></iframe>';
				}
				else
					$this->_linkDetail['thumb'] = '<iframe src="'.str_replace('vimeo.com','player.vimeo.com/video',$uri).'" width="100%" height="320" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
				$this->_linkDetail['imageCount'] = 0;
				$this->_linkDetail['images'] = array();
				$this->_linkDetail['isIframe'] = true;
			}

			if(!$this->_linkDetail['isGif'] && !$this->_linkDetail['isIframe']){
				// Get content-type
				list($contentType) = explode(';', $response->getHeader('content-type'));
				$this->_linkDetail['contentType'] = $contentType;

				// Prepare
				$this->_linkDetail['isGif'] = false;
				$this->_linkDetail['gifUrl'] = '';
				$this->_linkDetail['title'] = null;
				$this->_linkDetail['description'] = null;
				$this->_linkDetail['thumb'] = null;
				$this->_linkDetail['imageCount'] = 0;
				$this->_linkDetail['images'] = array();

				// Handling based on content-type
				switch( strtolower($contentType) ) {

					// Images
					case 'image/gif':
					case 'image/jpeg':
					case 'image/jpg':
					case 'image/tif': // Might not work
					case 'image/xbm':
					case 'image/xpm':
					case 'image/png':
					case 'image/bmp': // Might not work
						$this->_previewImage($uri, $response);
						break;

					// HTML
					case '':
					case 'text/html':
						$this->_previewHtml($uri, $response);
						break;

					// Plain text
					case 'text/plain':
						$this->_previewText($uri, $response);
						break;

					// Unknown
					default:
						break;
				}
			}
		}
		catch( Exception $e )
		{
			throw $e;
			//$this->_linkDetail['title = $uri;
			//$this->_linkDetail['description = $uri;
			//$this->_linkDetail['images = array();
			//$this->_linkDetail['imageCount = 0;
		}
		return $this->_linkDetail;
	}
	protected function _previewImage($uri, Zend_Http_Response $response)
	{
		$this->_linkDetail['imageCount'] = 1;
		$this->_linkDetail['images'] = array($uri);
	}

	protected function _previewText($uri, Zend_Http_Response $response)
	{
		$body = $response->getBody();
		if( preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getHeader('content-type'), $matches) ||
				preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getBody(), $matches) ) {
			$charset = trim($matches[1]);
		} else {
			$charset = 'UTF-8';
		}

		// Reduce whitespace
		$body = preg_replace('/[\n\r\t\v ]+/', ' ', $body);

		$this->_linkDetail['title'] = substr($body, 0, 63);
		$this->_linkDetail['description'] = substr($body, 0, 255);
	}

	protected function _previewHtml($uri, Zend_Http_Response $response)
	{
		$body = $response->getBody();
		$body = trim($body);
		if( preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getHeader('content-type'), $matches) ||
			preg_match('/charset=([a-zA-Z0-9-_]+)/i', $response->getBody(), $matches) ) {
			$this->_linkDetail['charset'] = $charset = trim($matches[1]);
		} else {
			$this->_linkDetail['charset'] = $charset = 'UTF-8';
		}
		if( function_exists('mb_convert_encoding') ) {
			$body = mb_convert_encoding($body, 'HTML-ENTITIES', $charset);
		}
		// Get DOM
		if( class_exists('DOMDocument') ) {
			$dom = new Zend_Dom_Query($body);
		} else {
			$dom = null; // Maybe add b/c later
		}
		$title = null;
		if( $dom ) {
			$titleList = $dom->query('title');
			if( engine_count($titleList) > 0 ) {
				$title = trim($titleList->current()->textContent);
			}
		}
		$this->_linkDetail['title'] = $title;
		$description = null;
		if( $dom ) {
			$descriptionList = $dom->queryXpath("//meta[@name='description']");
			// Why are they using caps? -_-
			if( engine_count($descriptionList) == 0 ) {
				$descriptionList = $dom->queryXpath("//meta[@name='Description']");
			}
			// Try to get description which is set under og tag
			if( engine_count($descriptionList) == 0 ) {
				$descriptionList = $dom->queryXpath("//meta[@property='og:description']");
			}
			if( engine_count($descriptionList) > 0 ) {
				$description = trim($descriptionList->current()->getAttribute('content'));
			}
		}
		$this->_linkDetail['description'] = $description;
		$thumb = null;
		if( $dom ) {
			$thumbList = $dom->queryXpath("//link[@rel='image_src']");
			$attributeType = 'href';
			if(engine_count($thumbList) == 0 ) {
				$thumbList = $dom->queryXpath("//meta[@property='og:image']");
				$attributeType = 'content';
			}
			if( engine_count($thumbList) > 0 ) {
				$thumb = $thumbList->current()->getAttribute($attributeType);
			}
		}
		$this->_linkDetail['thumb'] = $thumb;
		$medium = null;
		if( $dom ) {
			$mediumList = $dom->queryXpath("//meta[@name='medium']");
			if( engine_count($mediumList) > 0 ) {
				$medium = $mediumList->current()->getAttribute('content');
			}
		}
		$this->_linkDetail['medium'] = $medium;
		// Get baseUrl and baseHref to parse . paths
		$baseUrlInfo = parse_url($uri);
		$baseUrl = null;
		$baseHostUrl = null;
		$baseUrlScheme = $baseUrlInfo['scheme'];
		$baseUrlHost = $baseUrlInfo['host'];
		if( $dom ) {
			$baseUrlList = $dom->query('base');
			if( $baseUrlList && engine_count($baseUrlList) > 0 && $baseUrlList->current()->getAttribute('href') ) {
				$baseUrl = $baseUrlList->current()->getAttribute('href');
				$baseUrlInfo = parse_url($baseUrl);
				if( !isset($baseUrlInfo['scheme']) || empty($baseUrlInfo['scheme']) ) {
					$baseUrlInfo['scheme'] = $baseUrlScheme;
				}
				if( !isset($baseUrlInfo['host']) || empty($baseUrlInfo['host']) ) {
					$baseUrlInfo['host'] = $baseUrlHost;
				}
				$baseHostUrl = $baseUrlInfo['scheme'] . '://' . $baseUrlInfo['host'] . '/';
			}
		}
		if( !$baseUrl ) {
			$baseHostUrl = $baseUrlInfo['scheme'] . '://' . $baseUrlInfo['host'] . '/';
			if( empty($baseUrlInfo['path']) ) {
				$baseUrl = $baseHostUrl;
			} else {
				$baseUrl = explode('/', $baseUrlInfo['path']);
				array_pop($baseUrl);
				$baseUrl = join('/', $baseUrl);
				$baseUrl = trim($baseUrl, '/');
				$baseUrl = $baseUrlInfo['scheme'] . '://' . $baseUrlInfo['host'] . '/' . $baseUrl . '/';
			}
		}
		$images = array();
		if( $thumb ) {
			$images[] = $thumb;
		}
		if( $dom ) {
			$imageQuery = $dom->query('img');
			foreach( $imageQuery as $image ) {
				$src = $image->getAttribute('src');
				// Ignore images that don't have a src
				if( !$src || false === ($srcInfo = @parse_url($src)) ) {
					continue;
				}
				$ext = ltrim(strrchr($src, '.'), '.');
				// Detect absolute url
				if( strpos($src, '/') === 0 ) {
					// If relative to root, add host
					$src = $baseHostUrl . ltrim($src, '/');
				} elseif( strpos($src, './') === 0 ) {
					// If relative to current path, add baseUrl
					$src = $baseUrl . substr($src, 2);
				} elseif( !empty($srcInfo['scheme']) && !empty($srcInfo['host']) ) {
					// Contians host and scheme, do nothing
				} elseif( empty($srcInfo['scheme']) && empty($srcInfo['host']) ) {
					// if not contains scheme or host, add base
					$src = $baseUrl . ltrim($src, '/');
				} elseif( empty($srcInfo['scheme']) && !empty($srcInfo['host']) ) {
					// if contains host, but not scheme, add scheme?
					$src = $baseUrlInfo['scheme'] . ltrim($src, '/');
				} else {
					// Just add base
					$src = $baseUrl . ltrim($src, '/');
				}

				if( !engine_in_array($src, $images) ) {
					$images[] = $src;
				}
			}
		}
		// Unique
		$images = array_values(array_unique($images));
		// Truncate if greater than 20
		if( engine_count($images) > 30 ) {
			array_splice($images, 30, engine_count($images));
		}
		$this->_linkDetail['imageCount'] = engine_count($images);
		$this->_linkDetail['images'] = $images;
	}
}
