Thursday, November 18, 2010

Google map cluster with JSON

Google map cluster with JSON

When will cluster not work!.

I have identified that , if php script or any other server side script output in json and save it in file; and then use that file into google map cluster , then it will not work.

So don't use php or any other server side script which output in json in to system file, instead of json use direct values.

For ex:

// Get data from database and store it in $data variable.
// encode it in json
$json = json_encode($data);
// write it into "demo.json" file.
fwrite($fh, $json);

// use that file in map

$('#map_canvas').gmap().bind('init', function() {
    $.getJSON( 'http://localhost:90/testmapclustermarker/json/demo.json', function(data) {
 //put here marker cluster code, you can see cluster will not show/work.

    } );
    });

// == instead of above code use this below code ==

<div id="map_canvas" class="map" style="height:600px;"></div>
    <script type="text/javascript">
        //first use map api as:
        $('#map_canvas').gmap().bind('init', function(evt, map) {

// start here your server side programming tag:   
// connect to database and iterate it. don't store it in file system and don't convert it in json format.
// while not end database
// end here your server side programming tag:   

var marker_img="http://localhost:90/test/img/test.png";
$('#map_canvas').gmap('addMarker', {
                'position': new google.maps.LatLng(<?php echo (float)$row['lat'];?>,<?php echo (float)$row['log'];?>),
                'icon':new google.maps.MarkerImage(marker_img,new google.maps.Size(32,37)),
                'bounds': true,
                animation: google.maps.Animation.DROP,
            }).click(function() {                                    // marker.content
                $('#map_canvas').gmap('openInfoWindow', { 'content': "test"}, this);
            } );

// end loop database.
// set cluster here
var mcOptions = {gridSize: 50, maxZoom: 9, minimumClusterSize: 15, title: 'test'};
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map, $(this).gmap('get', 'markers'), mcOptions));
</script>




Make Profile Photo link in not working in social engine 4

Make Profile Photo link in not working in social engine 4

=====================================================
I was working in Social Engine 4 bug fix. I have found s bug , when user upload event's photo and if want to make it profile photo(by clicking on button) then nothing is happened. It was showing an server side error message.  To fix this problem, make listed below changes in .tpl and .php file  

=====================================================
Open "application/modules/Album/views/scripts/photo/view.tpl" file 
and replace listed below code:


<?php
  $this->headScript()
    ->appendFile($this->baseUrl() . '/externals/moolasso/Lasso.js')
    ->appendFile($this->baseUrl() . '/externals/moolasso/Lasso.Crop.js')
    ->appendFile($this->baseUrl() . '/externals/autocompleter/Observer.js')
    ->appendFile($this->baseUrl() . '/externals/autocompleter/Autocompleter.js')
    ->appendFile($this->baseUrl() . '/externals/autocompleter/Autocompleter.Local.js')
    ->appendFile($this->baseUrl() . '/externals/autocompleter/Autocompleter.Request.js')
    ->appendFile($this->baseUrl() . '/externals/tagger/tagger.js')
    ->appendFile($this->baseUrl() . '/application/modules/Album/externals/scripts/core.js');
  $this->headTranslate(array(
    'Save', 'Cancel', 'delete',
  ));
?>

<script type="text/javascript">
  var taggerInstance;
  en4.core.runonce.add(function() {
    var descEls = $$('.albums_viewmedia_info_caption');
    if( descEls.length > 0 ) {
      descEls[0].enableLinks();
    }

    taggerInstance = new Tagger('media_photo_next', {
      'title' : '<?php echo $this->string()->escapeJavascript($this->translate('ADD TAG'));?>',
      'description' : '<?php echo $this->string()->escapeJavascript($this->translate('Type a tag or select a name from the list.'));?>',
      'createRequestOptions' : {
        'url' : '<?php echo $this->url(array('module' => 'core', 'controller' => 'tag', 'action' => 'add'), 'default', true) ?>',
        'data' : {
          'subject' : '<?php echo $this->subject()->getGuid() ?>'
        }
      },
      'deleteRequestOptions' : {
        'url' : '<?php echo $this->url(array('module' => 'core', 'controller' => 'tag', 'action' => 'remove'), 'default', true) ?>',
        'data' : {
          'subject' : '<?php echo $this->subject()->getGuid() ?>'
        }
      },
      'cropOptions' : {
        'container' : $('media_photo_next')
      },
      'tagListElement' : 'media_tags',
      'existingTags' : <?php echo $this->action('retrieve', 'tag', 'core', array('sendNow' => false)) ?>,
      'suggestProto' : 'request.json',
      'suggestParam' : "<?php echo $this->url(array('module' => 'user', 'controller' => 'friends', 'action' => 'suggest', 'includeSelf' => true), 'default', true) ?>",
      'guid' : <?php echo ( $this->viewer()->getIdentity() ? "'".$this->viewer()->getGuid()."'" : 'false' ) ?>,
      'enableCreate' : <?php echo ( $this->canTag ? 'true' : 'false') ?>,
      'enableDelete' : <?php echo ( $this->canUntagGlobal ? 'true' : 'false') ?>
    });

    // Remove the href attrib while tagging
    var nextHref = $('media_photo_next').get('href');
    taggerInstance.addEvents({
      'onBegin' : function() {
        $('media_photo_next').erase('href');
      },
      'onEnd' : function() {
        $('media_photo_next').set('href', nextHref);
      }
    });

    window.addEvent('keyup', function(e) {
      if( e.target.get('tag') == 'html' ||
          e.target.get('tag') == 'body' ) {
        if( e.key == 'right' ) {
          window.location.href = "<?php echo ( $this->nextPhoto ? $this->nextPhoto->getHref() : 'window.location.href' ) ?>";
        } else if( e.key == 'left' ) {
          window.location.href = "<?php echo ( $this->previousPhoto ? $this->previousPhoto->getHref() : 'window.location.href' ) ?>";
        }
      }
    });
  });
</script>



<h2>
  <?php echo $this->translate('%1$s\'s Album: %2$s', $this->album->getOwner()->__toString(), $this->htmlLink($this->album, $this->album->getTitle())); ?>
</h2>

<?php if (""!=$this->album->getDescription()): ?>
  <p class="photo-description">
    <?php echo $this->album->getDescription() ?>
  </p>
<?php endif ?>

<div class="layout_middle">
<div class='albums_viewmedia'>
  <?php if( !$this->message_view): ?>
  <div class="albums_viewmedia_nav">
    <div>
      <?php echo $this->translate('Photo %1$s of %2$s in %3$s',
          $this->locale()->toNumber($this->photo->getPhotoIndex() + 1),
          $this->locale()->toNumber($this->album->count()),
          (string) $this->album->getTitle()) ?>
    </div>
    <?php if( $this->album->count() > 1 ): ?>
    <div>
      <?php echo $this->htmlLink(( $this->previousPhoto ? $this->previousPhoto->getHref() : null ), $this->translate('Prev')) ?>
      <?php echo $this->htmlLink(( $this->nextPhoto ? $this->nextPhoto->getHref() : null ), $this->translate('Next')) ?>
    </div>
    <?php endif ?>
  </div>
  <?php endif ?>
  <div class='albums_viewmedia_info'>
    <div class='album_viewmedia_container' id='media_photo_div'>
      <a id='media_photo_next'  href='<?php echo $this->nextPhoto ? $this->escape($this->nextPhoto->getHref()) : '#' ?>'>
        <?php echo $this->htmlImage($this->photo->getPhotoUrl(), $this->photo->getTitle(), array(
          'id' => 'media_photo'
        )); ?>
      </a>
    </div>
    <br />
    <a></a>
    <?php if( $this->photo->getTitle() ): ?>
      <div class="albums_viewmedia_info_title">
        <?php echo $this->photo->getTitle(); ?>
      </div>
    <?php endif; ?>
    <?php if( $this->photo->getDescription() ): ?>
      <div class="albums_viewmedia_info_caption">
        <?php echo nl2br($this->photo->getDescription()) ?>
      </div>
    <?php endif; ?>
    <div class="albums_viewmedia_info_tags" id="media_tags" style="display: none;">
      <?php echo $this->translate('Tagged:') ?>
    </div>
    <div class="albums_viewmedia_info_footer">
      <div class="albums_viewmedia_info_date">
        <?php echo $this->translate('Added %1$s', $this->timestamp($this->photo->modified_date)) ?>
        <?php if( $this->canTag ): ?>
          - <?php echo $this->htmlLink('javascript:void(0);', $this->translate('Add Tag'), array('onclick'=>'taggerInstance.begin();')) ?>
        <?php endif; ?>
        <?php if( $this->canEdit ): ?>
          - <?php echo $this->htmlLink(array('reset' => false, 'action' => 'edit'), $this->translate('Edit'), array('class' => 'smoothbox')) ?>
        <?php endif; ?>
        <?php if( $this->canDelete ): ?>
          - <?php echo $this->htmlLink(array('reset' => false, 'action' => 'delete'), $this->translate('Delete'), array('class' => 'smoothbox')) ?>
        <?php endif; ?>
        <?php if( !$this->message_view ):?>
        - <?php echo $this->htmlLink(Array('module'=> 'activity', 'controller' => 'index', 'action' => 'share', 'route' => 'default', 'type' => 'album_photo', 'id' => $this->photo->getIdentity(), 'format' => 'smoothbox'), $this->translate("Share"), array('class' => 'smoothbox')); ?>
        - <?php echo $this->htmlLink(Array('module'=> 'core', 'controller' => 'report', 'action' => 'create', 'route' => 'default', 'subject' => $this->photo->getGuid(), 'format' => 'smoothbox'), $this->translate("Report"), array('class' => 'smoothbox')); ?>
        - <?php echo $this->htmlLink(array('route' => 'user_extended', 'controller' => 'edit', 'action' => 'external-photo', 'photo' => $this->photo->getGuid(), 'format' => 'smoothbox'), $this->translate('Make Profile Photo'), array('class' => 'smoothbox')) ?>
        <?php endif;?>
      </div>
      <?php if( $this->canEdit ): ?>
      <div class="albums_viewmedia_info_actions">
        <a class="buttonlink icon_photos_rotate_ccw" href="javascript:void(0)" onclick="$(this).set('class', 'buttonlink icon_loading');en4.album.rotate(<?php echo $this->photo->getIdentity() ?>, 90).addEvent('complete', function(){ this.set('class', 'buttonlink icon_photos_rotate_ccw') }.bind(this));">&nbsp;</a>
        <a class="buttonlink icon_photos_rotate_cw" href="javascript:void(0)" onclick="$(this).set('class', 'buttonlink icon_loading');en4.album.rotate(<?php echo $this->photo->getIdentity() ?>, 270).addEvent('complete', function(){ this.set('class', 'buttonlink icon_photos_rotate_cw') }.bind(this));">&nbsp;</a>
        <a class="buttonlink icon_photos_flip_horizontal" href="javascript:void(0)" onclick="$(this).set('class', 'buttonlink icon_loading');en4.album.flip(<?php echo $this->photo->getIdentity() ?>, 'horizontal').addEvent('complete', function(){ this.set('class', 'buttonlink icon_photos_flip_horizontal') }.bind(this));">&nbsp;</a>
        <a class="buttonlink icon_photos_flip_vertical" href="javascript:void(0)" onclick="$(this).set('class', 'buttonlink icon_loading');en4.album.flip(<?php echo $this->photo->getIdentity() ?>, 'vertical').addEvent('complete', function(){ this.set('class', 'buttonlink icon_photos_flip_vertical') }.bind(this));">&nbsp;</a>
      </div>
      <?php endif ?>
    </div>
  </div>

  <?php echo $this->action("list", "comment", "core", array("type"=>"album_photo", "id"=>$this->photo->getIdentity())); ?>
</div>
</div>


=====================================================
Open "application/modules/User/controllers/EditController.php" file 
and replace listed below code:

<?php

class User_EditController extends Core_Controller_Action_User
{
  public function init()
  {
    if( !Engine_Api::_()->core()->hasSubject() ) {
      // Can specifiy custom id
      $id = $this->_getParam('id', null);
      $subject = null;
      if( null === $id ) {
        $subject = Engine_Api::_()->user()->getViewer();
        Engine_Api::_()->core()->setSubject($subject);
      } else {
        $subject = Engine_Api::_()->getItem('user', $id);
        Engine_Api::_()->core()->setSubject($subject);
      }
    }
   
    if( !empty($id) ) {
      $params = array('params' => array('id' => $id));
    } else {
      $params = array();
    }
    // Set up navigation
    $this->view->navigation = $navigation = Engine_Api::_()
      ->getApi('menus', 'core')
      ->getNavigation('user_edit', array('params'=>array('id'=>$id)));

    // Set up require's
    $this->_helper->requireUser();
    $this->_helper->requireSubject('user');
    $this->_helper->requireAuth()->setAuthParams(
      null,
      null,
      'edit'
    );
  }
 
  public function profileAction()
  {
    $this->view->user = $user = Engine_Api::_()->core()->getSubject();
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

    // remove styles if users are not allowed to style page
    $style_perm = Engine_Api::_()->getDbtable('permissions', 'authorization')->getAllowed('user', $user->level_id, 'style');
    if(!$style_perm) $this->view->navigation->removePage(2);

   
    // General form w/o profile type
    $aliasedFields = $user->fields()->getFieldsObjectsByAlias();
    $this->view->topLevelId = $topLevelId = 0;
    $this->view->topLevelValue = $topLevelValue = null;
    if( isset($aliasedFields['profile_type']) ) {
      $aliasedFieldValue = $aliasedFields['profile_type']->getValue($user);
      $topLevelId = $aliasedFields['profile_type']->field_id;
      $topLevelValue = ( is_object($aliasedFieldValue) ? $aliasedFieldValue->value : null );
      if( !$topLevelId || !$topLevelValue ) {
        $topLevelId = null;
        $topLevelValue = null;
      }
      $this->view->topLevelId = $topLevelId;
      $this->view->topLevelValue = $topLevelValue;
    }
   
    // Get form
    $form = $this->view->form = new Fields_Form_Standard(array(
      'item' => Engine_Api::_()->core()->getSubject(),
      'topLevelId' => $topLevelId,
      'topLevelValue' => $topLevelValue,
    ));
    //$form->generate();
   
    // Not posting
    if( $this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost()) )
    {
      $form->saveValues();

      // Update display name
      $aliasValues = Engine_Api::_()->fields()->getFieldsValuesByAlias($user);
      $user->setDisplayName($aliasValues);
      //$user->modified_date = date('Y-m-d H:i:s');
      $user->save();

      // update networks
      Engine_Api::_()->network()->recalculate($user);
     
      $form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
    }
  }


  public function photoAction()
  {
    $this->view->user = $user = Engine_Api::_()->core()->getSubject();
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

    // remove styles if users are not allowed to style page
    $style_perm = Engine_Api::_()->getDbtable('permissions', 'authorization')->getAllowed('user', $user->level_id, 'style');
    if( !$style_perm ) {
      $this->view->navigation->removePage(2);
    }

    // Get form
    $this->view->form = $form = new User_Form_Edit_Photo();

    if( empty($user->photo_id) ) {
      $form->removeElement('remove');
    }

    if( !$this->getRequest()->isPost() ) {
      return;
    }

    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    // Uploading a new photo
    if( $form->Filedata->getValue() !== null ) {
      $db = $user->getTable()->getAdapter();
      $db->beginTransaction();
     
      try {
        $fileElement = $form->Filedata;

        $user->setPhoto($fileElement);
       
        $iMain = Engine_Api::_()->getItem('storage_file', $user->photo_id);
       
        // Insert activity
        $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $user, 'profile_photo_update',
          '{item:$subject} added a new profile photo.');

        // Hooks to enable albums to work
        if( $action ) {
          $event = Engine_Hooks_Dispatcher::_()
            ->callEvent('onUserProfilePhotoUpload', array(
                'user' => $user,
                'file' => $iMain,
              ));

          $attachment = $event->getResponse();
          if( !$attachment ) $attachment = $iMain;

          // We have to attach the user himself w/o album plugin
          Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $attachment);
        }
       
        $db->commit();
      }

      // If an exception occurred within the image adapter, it's probably an invalid image
      catch( Engine_Image_Adapter_Exception $e )
      {
        $db->rollBack();
        $form->addError(Zend_Registry::get('Zend_Translate')->_('The uploaded file is not supported or is corrupt.'));
      }

      // Otherwise it's probably a problem with the database or the storage system (just throw it)
      catch( Exception $e )
      {
        $db->rollBack();
        throw $e;
      }
    }

    // Resizing a photo
    else if( $form->getValue('coordinates') !== '' ) {
      $storage = Engine_Api::_()->storage();

      $iProfile = $storage->get($user->photo_id, 'thumb.profile');
      $iSquare = $storage->get($user->photo_id, 'thumb.icon');

      // Read into tmp file
      $pName = $iProfile->getStorageService()->temporary($iProfile);
      $iName = dirname($pName) . '/nis_' . basename($pName);

      list($x, $y, $w, $h) = explode(':', $form->getValue('coordinates'));

      $image = Engine_Image::factory();
      $image->open($pName)
        ->resample($x+.1, $y+.1, $w-.1, $h-.1, 48, 48)
        ->write($iName)
        ->destroy();

      $iSquare->store($iName);

      // Remove temp files
      @unlink($iName);
    }
  }

  public function removePhotoAction()
  {
    // Get form
    $this->view->form = $form = new User_Form_Edit_RemovePhoto();

    if( !$this->getRequest()->isPost() || !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }
   

    $user = Engine_Api::_()->core()->getSubject();
    $user->photo_id = 0;
    $user->save();
   
    $this->view->status = true;
    $this->view->message = Zend_Registry::get('Zend_Translate')->_('Your photo has been removed.');

    $this->_forward('success', 'utility', 'core', array(
      'smoothboxClose' => true,
      'parentRefresh' => true,
      'messages' => array(Zend_Registry::get('Zend_Translate')->_('Your photo has been removed.'))
    ));
  }

  public function styleAction()
  {
    $this->view->user = $user = Engine_Api::_()->core()->getSubject();
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    if( !$this->_helper->requireAuth()->setAuthParams('user', null, 'style')->isValid()) return;


    // Get form
    $this->view->form = $form = new User_Form_Edit_Style();

    // Get current row
    $table = Engine_Api::_()->getDbtable('styles', 'core');
    $select = $table->select()
      ->where('type = ?', $user->getType())
      ->where('id = ?', $user->getIdentity())
      ->limit();

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

    // Not posting, populate
    if( !$this->getRequest()->isPost() )
    {
      $form->populate(array(
        'style' => ( null === $row ? '' : $row->style )
      ));
      return;
    }

    // Whoops, form was not valid
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Cool! Process
    $style = $form->getValue('style');

    // Process
    $style = strip_tags($style);

    $forbiddenStuff = array(
      '-moz-binding',
      'expression',
      'javascript:',
      'behaviour:',
      'vbscript:',
      'mocha:',
      'livescript:',
    );

    $style = str_replace($forbiddenStuff, '', $style);

    // Save
    if( null == $row )
    {
      $row = $table->createRow();
      $row->type = $user->getType();
      $row->id = $user->getIdentity();
    }

    $row->style = $style;
    $row->save();

    $form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
  }

  public function externalPhotoAction()
  {
    if( !$this->_helper->requireSubject()->isValid() ) return;
    $user = Engine_Api::_()->core()->getSubject();
   
    // Get photo
    $photo = Engine_Api::_()->getItemByGuid($this->_getParam('photo'));
    if( !$photo || !($photo instanceof Core_Model_Item_Abstract) || empty($photo->photo_id) ) {
      $this->_forward('requiresubject', 'error', 'core');
      return;
    }

    if( !$photo->authorization()->isAllowed(null, 'view') ) {
      $this->_forward('requireauth', 'error', 'core');
      return;
    }

   
    // Make form
    $this->view->form = $form = new User_Form_Edit_ExternalPhoto();
    $this->view->photo = $photo;

    if( !$this->getRequest()->isPost() ) {
      return;
    }

    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    // Process
    $db = $user->getTable()->getAdapter();
    $db->beginTransaction();
   
    try {
      // Get the owner of the photo
      $photoOwnerId = null;
      if( isset($photo->user_id) ) {
        $photoOwnerId = $photo->user_id;
      } else if( isset($photo->owner_id) && (!isset($photo->owner_type) || $photo->owner_type == 'user') ) {
        $photoOwnerId = $photo->owner_id;
      }

      // if it is from your own profile album do not make copies of the image
      if( $photo instanceof Album_Model_Photo &&
          ($photoParent = $photo->getParent()) instanceof Album_Model_Album &&
          $photoParent->owner_id == $photoOwnerId &&
          $photoParent->type == 'profile' ) {

        // ensure thumb.icon and thumb.profile exist
        $newStorageFile = Engine_Api::_()->getItem('storage_file', $photo->file_id);
        $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
        if( $photo->file_id == $filesTable->lookupFile($photo->file_id, 'thumb.profile') ) {
          try {
            $tmpFile = $newStorageFile->temporary();
            $image = Engine_Image::factory();
            $image->open($tmpFile)
              ->resize(200, 400)
              ->write($tmpFile)
              ->destroy();
            $iProfile = $filesTable->createFile($tmpFile, array(
              'parent_type' => $user->getType(),
              'parent_id' => $user->getIdentity(),
              'user_id' => $user->getIdentity(),
              'name' => basename($tmpFile),
            ));
            $newStorageFile->bridge($iProfile, 'thumb.profile');
            @unlink($tmpFile);
          } catch( Exception $e ) { echo $e; die(); }
        }
        if( $photo->file_id == $filesTable->lookupFile($photo->file_id, 'thumb.icon') ) {
          try {
            $tmpFile = $newStorageFile->temporary();
            $image = Engine_Image::factory();
            $image->open($tmpFile);
            $size = min($image->height, $image->width);
            $x = ($image->width - $size) / 2;
            $y = ($image->height - $size) / 2;
            $image->resample($x, $y, $size, $size, 48, 48)
              ->write($tmpFile)
              ->destroy();
            $iSquare = $filesTable->createFile($tmpFile, array(
              'parent_type' => $user->getType(),
              'parent_id' => $user->getIdentity(),
              'user_id' => $user->getIdentity(),
              'name' => basename($tmpFile),
            ));
            $newStorageFile->bridge($iSquare, 'thumb.icon');
            @unlink($tmpFile);
          } catch( Exception $e ) { echo $e; die(); }
        }

        // Set it
        $user->photo_id = $photo->file_id;
        $user->save();
       
        // Insert activity
        // @todo maybe it should read "changed their profile photo" ?
        $action = Engine_Api::_()->getDbtable('actions', 'activity')
            ->addActivity($user, $user, 'profile_photo_update',
                '{item:$subject} changed their profile photo.');
        if( $action ) {
          // We have to attach the user himself w/o album plugin
          Engine_Api::_()->getDbtable('actions', 'activity')
              ->attachActivity($action, $photo);
        }
      }

      // Otherwise copy to the profile album
      else {
        $user->setPhoto($photo);

        // Insert activity
        $action = Engine_Api::_()->getDbtable('actions', 'activity')
            ->addActivity($user, $user, 'profile_photo_update',
                '{item:$subject} added a new profile photo.');
       
        // Hooks to enable albums to work
        $newStorageFile = Engine_Api::_()->getItem('storage_file', $user->photo_id);
        $event = Engine_Hooks_Dispatcher::_()
          ->callEvent('onUserProfilePhotoUpload', array(
              'user' => $user,
              'file' => $newStorageFile,
            ));

        $attachment = $event->getResponse();
        if( !$attachment ) {
          $attachment = $newStorageFile;
        }
       
        if( $action  ) {
          // We have to attach the user himself w/o album plugin
          Engine_Api::_()->getDbtable('actions', 'activity')
              ->attachActivity($action, $attachment);
        }
      }

      $db->commit();
    }

    // Otherwise it's probably a problem with the database or the storage system (just throw it)
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
   
    return $this->_forward('success', 'utility', 'core', array(
      'messages' => array(Zend_Registry::get('Zend_Translate')->_('Set as profile photo')),
      'smoothboxClose' => true,
    ));
  }

  public function clearStatusAction()
  {
    $this->view->status = false;
   
    if( $this->getRequest()->isPost() ) {
      $viewer = Engine_Api::_()->user()->getViewer();
      $viewer->status = '';
      $viewer->status_date = '00-00-0000';
      // twitter-style handling
      // $lastStatus = $viewer->status()->getLastStatus();
      // if( $lastStatus ) {
      //   $viewer->status = $lastStatus->body;
      //   $viewer->status_date = $lastStatus->creation_date;
      // }
      $viewer->save();
     
      $this->view->status = true;
    }
  }
}

Wednesday, November 17, 2010

Multiple and single words count algorithm

<?php
// Multiple and single words suggestion algorithm.


    $words="this is a programming language. the programming language is only for smart humans or aliens in the all universe. There are lot of programming language available. The most popular programming language Java. programming language Java is very poupular due to its robustness. programming language Java programming language Java programming language Java programming language Java testing testing testing testing testing testing testing testing testing testing testing";
   
    echo $words."<br>";
    $words=str_replace(array(".",",",";",":"),"",$words);
    $res=array();
    $wArr=explode(" ",$words);
    $nArr=explode(" ",$words);
   
    $res=getSingleCount($wArr);
    echo "<br>Single words suggestion<br>=========================<br>";
    for($i=0;$i<count($res);$i++)
        echo $res[$i][0]."=".$res[$i][1]."<br>";
   
    echo "<br>Double words suggestion? just use n-1 number, where n is equals to 2<br>=========================<br>";
    $res2=getMultiSuggest($nArr,1,$words);
    for($i=0;$i<count($res2);$i++)
        echo $res2[$i][0]."=".$res2[$i][1]."<br>";
   
   
    echo "<br><br>Triple words suggestion? just use n-1 number, where n is equals to 3<br>=========================<br>";
    $res3=getMultiSuggest($nArr,2,$words);
    for($i=0;$i<count($res3);$i++)
        echo $res3[$i][0]."=".$res3[$i][1]."<br>";
   
   
    echo "<br><br>Four words suggestion? just use n-1 number, where n is equals to 4<br>=========================<br>";
    $res3=getMultiSuggest($nArr,3,$words);
    for($i=0;$i<count($res3);$i++)
        echo $res3[$i][0]."=".$res3[$i][1]."<br>";
   
    function getSingleCount($wArr) {
        for($i=0;$i<count($wArr);$i++) {
            $c=0;
            if($wArr[$i]=="")
                continue;
            for($j=1+$i;$j<count($wArr);$j++) {
                if($wArr[$i]!="" && $wArr[$j]!="") {
                    if(strtolower ($wArr[$i])==strtolower ($wArr[$j])) {
                        $c++;
                        $wArr[$j]="";
                    }
                }
            }
            $res[]= array($wArr[$i] , ++$c);
        }
        return $res;
    }
   
    function getMultiSuggest($nArr,$num,$fullSent) {
        $tt=$fullSent;
        $res=array();
       
        for($i=0;$i<count($nArr)-1;$i++) {
            $sWords="";
            for($j=$i;$j<=$i+$num && $j<count($nArr); $j++) {
                $sWords.=$nArr[$j]. " ";
            }
            $sWords=trim($sWords);
            $m=count(explode(" ",$sWords));
            $w=preg_match_all("/\b".$sWords."\b/i", $tt,$out);
            if($m==$num+1){
                if($w>1) {
                    $found=FALSE;
                    if(count($res)>=0) {
                        for($k=0;$k<count($res);$k++) {
                            if($res[$k][0]==$sWords) {
                                $found=TRUE;
                                break;
                            }
                        }
                    }
                    if($found==FALSE){
                        $res[]= array($sWords , $w);
                    }
                }
            }
               
        }
        return $res;   
    }
?>

Tuesday, November 16, 2010

Restricted access error in Joomla

'Restricted access' error in Joomla

When you work in Joomla, you can get the most common error 'Restricted access' error.
There many possibilities that show this error, but the most common mistake is to write incorrect statement.
you can write:
define('JEXEC') or die ('Restricted access');

but the corrected format is :
defined('JEXEC') or die ('Restricted access');  and run the page.
and Wow!!! you can get the same error message. now this is the time to more correct format is:
defined('_JEXEC') or die('Restricted access');

now run the page , you will not get the error.