Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * SocialEngine
- *
- * @category
- * @package
- * @copyright
- * @license
- * @version
- * @author Danilo Ronca
- */
- /**
- * @category
- * @package
- * @copyright
- * @license
- */
- class Rest_Api_Auxiliary extends Core_Api_Abstract {
- static $usersCollection = "users";
- private static $photosColl = 'photos';
- private static $conversationsColl = 'conversations';
- private static $messagesColl = 'messages';
- private static $notificationsColl = 'notifications';
- private static $offersColl = 'offers';
- private static $feedsColl = 'feeds';
- private static $followersColl = 'user_relationships';
- private static $photosTaskColl = 'photos_task';
- private static $postsColl = 'posts';
- private static $photoSeeColl = 'photosee';
- private static $eventsColl = 'events';
- private static $eventMemberColl = 'event_membership';
- private static $offersCategoriesCollection = 'offer_categories';
- private static $offerCurrenciesCollection = 'offer_currencies';
- private static $offerLimitationTypes = 'offer_limitation_types';
- private static $offersTaskColl = 'offers_task';
- /**
- * This method remove the record that has the device_id specified
- * in the device table.
- * @param $device_id deviceID to delete
- */
- public function removeDevice($device_id, $owner_id = null) {
- if($owner_id != null) {
- $where = array("_id" => $owner_id, 'devices' => array('$elemMatch' => array('id' => $device_id)));
- } else {
- $where = array('devices' => array('$elemMatch' => array('id' => $device_id)));
- }
- MyMongo_Connection::pullCollectionFields(static::$usersCollection, $where, array('devices' => array("id" => $device_id)));
- }
- /**
- * Ottiene i messaggi dell'utente nella conversazione specificata.
- * Setta sia la conversazione a letta, che la notifica su di essa a letta.
- * @param $conversation_id
- * @param $endDate
- * @param $userID
- * @return array dei messaggi
- */
- public function getMessagesConversation($conversation_id,$endDate,$userID,$fromWS=false, $limit=null)
- {
- //ottengo i messaggi della conversazione specificata (gli eliminati non compariranno)
- $messagesInConversation = Engine_Api::_ ()->getApi ( "messageutility", "messages" )->
- getConversationParticipantsDetails($conversation_id, $userID,-1,false,$limit,$endDate);
- $arrayMessages = array();
- $i=0;
- foreach ($messagesInConversation as $currMessage)
- {
- $arrayMessages[$i]['msg_id'] = !$fromWS ? $currMessage["_id"] : $currMessage["_id"]->__toString();
- $arrayMessages[$i]['message'] = $currMessage["body"];
- $arrayMessages[$i]['sender'] = $this->getUserDetails($currMessage["sender_id"]);
- $arrayMessages[$i]['sending_date'] = $currMessage["creation_date"]->sec;
- $i++;
- }
- //Setto la conversazione a letta
- MyMongo_Connection::updateCollectionFields
- (
- static::$conversationsColl,
- array('conversation_id' => $conversation_id, 'owner_id' => $userID),
- array('read' => true)
- );
- //setto la notifica a true
- MyMongo_Connection::updateCollectionFields
- (
- static::$notificationsColl,
- array('user_id' => $userID, 'object_type' => 'conversation', 'object_id' => $conversation_id),
- array('read' => true)
- );
- return $arrayMessages;
- }
- /**
- * Aggiunge un document nella collection dei photosee: si occupa anche del calcolo della distanza,
- * aggiornamento dei contatori e varie sul document relativo alla foto specificata.
- * @param $photo
- * @param $user_id
- * @param $latitude
- * @param $longitude
- * @return array with the id of created record and the counter of views.
- */
- public function createPhotoSeeRecord($photo, $user_id, $latitude, $longitude)
- {
- ini_set('mongo.native_long', 1);
- $condition = array
- (
- 'photo_id' => $photo->_id,
- 'lat' => $latitude,
- 'lon' => $longitude,
- );
- $penultimatSeeCursor = MyMongo_Connection::find(static::$photoSeeColl, array('photo_id' => $photo->_id), array(), array('move_date' => -1), 1);
- //questo sarà il penultimo insieme di photosee (in ordine temporale discendente) dopo l'aggiunta di quello che si sta per creare: serve per l'eventuale aggiornamento delle distance
- $penultimatSeeSet = null;
- if($penultimatSeeCursor->hasNext())
- {
- $penultimatSeeSet = $penultimatSeeCursor->getNext();
- }
- $geoArray = $this->Get_Address_From_Google_Maps($latitude, $longitude);
- $city = (sizeof($geoArray) != 0) ? $geoArray["city"] : "NULL";
- //$mongoQuery = 'db.photosee.update({photo_id:"'.$photo->_id.'",lat:"'.$latitude.'",lon:"'.$longitude.'"},{$inc:{count:1}, $addToSet:{viewers:{user_id : "'.$user_id.'"}} ,$setOnInsert:{lat:"'.$latitude.'",lon:"'.$longitude.'",city:"'.$city.'",mover:"'.$user_id.'",move_date:ISODate()}},{upsert:true})';
- //$result = MyMongo_Connection::executeEvaluation($mongoQuery);
- $result = MyMongo_Connection::getConnection()->selectCollection("photosee")->update(
- array("photo_id" => $photo->_id, "lat" => $latitude, "lon" => $longitude),
- array(
- '$inc' => array("count" => 1),
- '$addToSet' => array("viewers" => array("user_id" => $user_id)),
- '$setOnInsert' => array("lat" => $latitude, "lon" => $longitude, "city" => $city, "mover" => $user_id, "move_date" => new MongoDate())
- ),
- array("upsert" => true)
- );
- $arrayValueToInsert = array();
- //Se la foto non ha un uploader
- if(empty($photo->position_uploader))
- {
- $arrayValueToInsert["upload_position"] = array('lat'=>$latitude, 'lon' => $longitude, 'city' => $city);
- $arrayValueToInsert["position_uploader"] = $user_id;
- //salva la mappa statica e ne ottiene l'url in cui è stata salvata
- $arrayValueToInsert["map_upload_img_url"] = Engine_Api::_()->getApi('googleutility', 'core')->saveStaticPhotoMap($latitude, $longitude);
- }
- $incrementArr = array('photosee_count' => 1);
- //se non c'era un document relativo ai photosee in queste coordinate, allora devo incrementare i move e la distanza
- if($result['nModified'] == 0)
- {
- $penultimateSeeLat = null;
- $penultimateSeeLon = null;
- //se è presente la posizione di upload e non ci sono photosee
- if(!empty($photo->position_uploader) && $photo->photosee_count === 0)
- {
- $penultimateSeeLat = $photo->upload_position['lat'];
- $penultimateSeeLon = $photo->upload_position['lon'];
- }
- //se invece c'è la coordinata di upload e ci sono anche photosee
- else if(!empty($photo->position_uploader) && $photo->photosee_count > 0)
- {
- //se c'è già un photo see si deve calcolare distanza da penultimo
- $penultimateSeeLat = $penultimatSeeSet['lat'];
- $penultimateSeeLon = $penultimatSeeSet['lon'];
- }
- if(!is_null($penultimateSeeLat) && !is_null($penultimateSeeLon))
- {
- $incrementArr['moves_count'] = 1;//incrementa di 1 i moves
- //the distance between lat and lon given in input and lat and lon where the last photo has seen + old distance
- $tmpDistance = $this->distance($penultimateSeeLat, $penultimateSeeLon, $latitude, $longitude, "M") ;
- $arrayValueToInsert['distance'] = $tmpDistance + $photo->distance;
- }
- }
- // //aggiorno le informazioni in foto
- MyMongo_Connection::updateAndOrIncCollectionFields
- (
- static::$photosColl,
- array('_id' => $photo->_id),
- $arrayValueToInsert,
- $incrementArr
- );
- //Invio delle notifiche inizio
- $isMoved = array_key_exists('moves_count', $incrementArr);//true se la foto è stata spostata ("moved")
- $this->addPhotoSeeNotifications($photo, $user_id, $isMoved);
- //Invio delle notifiche fine
- return array(/*"see_id" => $photosee['photosee_id'], */"see_count" => $photo->photosee_count + 1);
- }
- /**
- * Questo metodo si occupa dell'invio delle notifiche: photo_seen, photo_seen_seen, photo_moved
- * @param $photoObj
- * @param $user_id
- * @param $isMoved true se la foto è stata moved, false altrimenti
- */
- public function addPhotoSeeNotifications($photoObj, $user_id, $isMoved)
- {
- $photoOwnerID = $photoObj->owner_id;
- //ottengo la lista di tutti gli utenti che hanno visto la foto
- $seeUsers = Utilities_Static::getPhotoutility()->getPhotoSeeUsers($photoObj->_id);
- //se owner e user che richiede sono diversi
- if(strcasecmp($photoOwnerID, $user_id) != 0)
- {
- //invio una notifica di photoseen all'owner della foto
- Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification
- ($photoOwnerID, $user_id, $photoObj->_id, 'photo', 'photo_seen');
- //Se la foto è stata spostata si notifica all'owner
- if($isMoved)
- {
- //invio una notifica di photo moved all'owner della foto
- Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification
- ($photoOwnerID, $user_id, $photoObj->_id, 'photo', 'photo_moved');
- }
- //rimuove owner e utente corrente dalla lista se erano eventualmente presenti
- $seeUsers = array_diff($seeUsers, array($photoOwnerID, $user_id));
- }
- else
- {
- //rimuove owner dalla lista se eventualmente presente
- $seeUsers = array_diff($seeUsers, array($photoOwnerID));
- }
- //invio di notifiche di tipo photo seen seen
- foreach ($seeUsers as $currViewerID)
- {
- //invio la notifica al current user id dicendogli che anche $user_id ha visto una foto che lui ha visto
- Engine_Api::_()->getDbtable('notifications', 'activity')->addNotificationExceptPushNotification
- ($currViewerID, $user_id, $photoObj->_id, 'photo', 'photo_seen_seen');
- }
- //invio al push a tutti gli utenti che hanno visto gia' la foto
- Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($seeUsers);
- return;
- }
- /**
- * This function return an array indicating the position earned(>0), lost(<0) or stable(=0) and
- * the days passed from latest update (including current and previous rank).
- * @param $user
- * @return array
- */
- public function getSocialmaticRanking($user) {
- if(!is_object($user)) {
- $user = (object) $user;
- }
- $dayPassedFromUpdate = $this->getDistanceDayBetweenTwoDateWithoutTimeZone(date('Y-m-d H:i:s', time()), date('Y-m-d H:i:s', $user->update_rank_date->sec));
- return array(
- "positions" => $user->previous_rank - $user->current_rank,
- "dayPassedFromUpdate" => round($dayPassedFromUpdate, 2, PHP_ROUND_HALF_DOWN),
- "current_rank" => $user->current_rank,
- "previous_rank" => $user->previous_rank
- );
- }
- /**
- * This method checks if the date of first photo passed in oldest than nDays and
- * if the photoDatesArray is more than kPhotos.
- * @param $photoDatesArray
- * @param $kPhotos
- * @param $nDays
- * @return boolean
- */
- public function checkMoreThanKPhotosInNDays($photoDatesArray, $kPhotos, $nDays)
- {
- //if there are less photo than K
- if(sizeof($photoDatesArray) <= $kPhotos)
- return false;
- else
- {
- $oldestDataInfo = $this->getOldestPhotoData($photoDatesArray);
- if( $this->getDistanceDaysFromToday($oldestDataInfo["oldestDate"]) > $nDays)
- return false;
- else return true;
- }
- }
- /**
- * This method return the oldest data of data's array given in input
- * @param $array_photo_dates (each data is e.g. 2013-11-04 20:25:18+09:00)
- * @return mixed
- */
- public function getOldestPhotoData($array_photo_dates)
- {
- $normalized_datas_received = array(); // @strtotime(date_format($dt, 'Y-m-d H:i:s'));
- $arrDatas = array();
- $i=0;
- foreach ($array_photo_dates as $currDate)
- {
- $arrDatas["".@strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'))] = $currDate;
- $normalized_datas_received[$i] = @strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'));
- $i++;
- }
- $timeMillis = min($normalized_datas_received);
- $lastDate = $arrDatas[$timeMillis];
- return array("time" => $timeMillis, "oldestDate" => $lastDate);
- }
- /**
- * This method returns the first N photos dates uploaded by the user_id
- * @param $userID
- * @param $numberLimit
- * @return array of last n photo shared by the user
- */
- public function getFirstNSharedPhoto($userID, $numberLimit)
- {
- $arrayLastNPhoto = array();
- $resultPhoto = MyMongo_Connection::find(
- static::$photosColl,
- array('owner_id'=>$userID),
- array('creation_date' => 1), //seleziono
- array('creation_date' => 1), //ordino asc
- $numberLimit);
- foreach ($resultPhoto as $currPhotoRecord)
- {
- array_push($arrayLastNPhoto, $currPhotoRecord['creation_date']);
- }
- return $arrayLastNPhoto;
- }
- /**
- * This method return the day passed from the last photo to now.
- * @param $array_photo_dates array of dates
- * @return distance from the latest date today
- */
- public function getDaysFromLastPhoto($array_photo_dates)
- {
- $lastDataInfo = $this->getLastPhotoData($array_photo_dates);
- return $this->getDistanceDaysFromToday($lastDataInfo["lastDate"]);
- }
- /**
- * This method return the last date of date's array given in input
- * @param $array_photo_dates (each data is e.g. 2013-11-04 20:25:18+09:00)
- * @return array with the currentMillis and normalized string (e.g. 2013-11-04 20:25:18) of last date
- */
- public function getLastPhotoData($array_photo_dates)
- {
- $normalized_datas_received = array(); // @strtotime(date_format($dt, 'Y-m-d H:i:s'));
- $arrDatas = array();
- $i=0;
- foreach ($array_photo_dates as $currDate)
- {
- $arrDatas["".@strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'))] = $currDate;
- $normalized_datas_received[$i] = @strtotime(date_format(new DateTime($currDate), 'Y-m-d H:i:s'));
- $i++;
- }
- $timeMillis = max($normalized_datas_received);
- $lastDate = $arrDatas[$timeMillis];
- return array("time" => $timeMillis, "lastDate" => $lastDate);
- }
- /**
- * This method returns the days passed from today's date to the date on input.
- * It considers the timezone, hence it compute the day passed in that
- * time zone .
- * @param $timeReceived is a string representing a time (e.g. $timeReceived='2013-11-04 19:20:18+09:00')
- * @return the distance in day between timeReceived and today.
- */
- public function getDistanceDaysFromToday($timeReceived)
- {
- /*Time information about server current zone*/
- $now = date('Y-m-d H:i:s', time());
- $timeHere = new DateTime($now, new DateTimeZone(ini_get('date.timezone')));
- //echo $timeHere->format('Y-m-d H:i:sP') . "<br />";
- /*Time information about server current zone*/
- /*Time information about remote zone*/
- $dt = new DateTime($timeReceived);
- $nowtimeInThatTZ=$timeHere->setTimezone(new DateTimeZone($this->myGetTimeZone($dt->getTimezone()->getName())));
- //echo $nowtimeInThatTZ->format('Y-m-d H:i:sP') . "<br />";
- /*Time information about remote zone*/
- $normalized_data_received = @strtotime(date_format($dt, 'Y-m-d H:i:s'));
- $normalized_nowtimeInThatTZ = @strtotime(date_format($nowtimeInThatTZ, 'Y-m-d H:i:s'));
- //compute the difference in days between the dates
- $datediff = $normalized_nowtimeInThatTZ - $normalized_data_received;
- return $datediff/(60*60*24);
- }
- /**
- * This method return the difference in day from date1 and date2. It doesn't consider the time zone.
- * @param $date1
- * @param $date2
- * @return difference in day between $date1 and $date2 ($date1 - $date2)
- */
- public function getDistanceDayBetweenTwoDateWithoutTimeZone($date1, $date2)
- {
- $dt1 = new DateTime($date1);
- $dt2 = new DateTime($date2);
- $normalized_data1 = @strtotime(date_format($dt1, 'Y-m-d H:i:s'));
- $normalized_data2 = @strtotime(date_format($dt2, 'Y-m-d H:i:s'));
- //compute the difference in days between the dates
- $datediff = $normalized_data1 - $normalized_data2;
- return $datediff/(60*60*24);
- }
- /**
- * Get the user's info.
- *
- * @param $arrayUserID
- * @return array representing the user's information.
- */
- public function getUserDetails($arrayUserID, $interestWithCategory=false)
- {
- //se è un id
- if(is_string($arrayUserID))
- {
- $user = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $arrayUserID));
- if(!is_null($user))
- {
- return $this->buildUserArr((array)$user, $interestWithCategory);
- }
- else
- {
- return array();
- }
- }
- else
- {
- if (sizeof($arrayUserID) > 0)
- {
- $arrayUsersInfo = MyMongo_Connection::find(static::$usersCollection, array('_id' => array('$in' => $arrayUserID)));
- $userInfo = array();
- $element = null;
- foreach ($arrayUsersInfo as $user)
- {
- $element = $this->buildUserArr($user, $interestWithCategory);
- $userInfo[] = $element;
- }
- if(is_null($element))
- {
- return $this->buildDetedUser();
- }
- if(sizeof($userInfo) == 1)
- return $element;
- else
- {
- return $userInfo;
- }
- }
- else
- {
- return array();
- }
- }
- }
- /**
- * Costruisce un item utente sotto forma di array
- * @param $user array dell'utente restituito dalla query
- * @param $interestWithCategory se è vero restituisce anche la ce
- */
- public function buildUserArr($user, $interestWithCategory=false)
- {
- $element = array(
- 'user_id' => $user["_id"],
- 'nickname' => $user["username"],
- 'status' => $user["status"],
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/" . "profile/" . $user["username"],
- 'ranking' => $user["current_rank"],
- );
- $element["positions_ranking"] = $user["current_rank"] - $user["previous_rank"];
- $interests = !$interestWithCategory ? Utilities_Static::getUserutility()->getUserInterests((object)$user, false) : $user['interests'];
- $element["interests"] = is_null($interests) ? array() : $interests;
- $element["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($user["_id"]);
- $element["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($user, true);
- $userType = ucfirst($user["type"]);
- $element["user_type"] = $userType;
- if (strcasecmp($userType, "personal") == 0)
- {
- $element["user_gender"] = $user["gender"];
- }
- return $element;
- }
- /**
- * Get the user's info.
- *
- * @param $arrayUserIDs
- * @return array representing the user's information.
- */
- public function getUserDetailsToArray($arrayUserIDs, $viewerID=null)
- {
- if (sizeof($arrayUserIDs) > 0)
- {
- $userUtility = Engine_Api::_()->getApi ( 'userutility', 'core' );
- $userInfo = array();
- foreach ($arrayUserIDs as $user)
- {
- $element = array(
- 'user_id' => $user["_id"],
- 'display_name' => $userUtility->getNameOrCompanyOfUser($user),
- 'nickname' => $user["username"],
- 'status' => $user["status"],
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/" . "profile/" . $user["username"],
- 'ranking' => $user["current_rank"],
- );
- $element["positions_ranking"] = $user["current_rank"] - $user["previous_rank"];
- $element["interests"] = array();
- if(!is_null($user["interests"]))
- {
- $element["interests"] = $user["interests"];
- $dimInterests = sizeof($element["interests"]);
- for($i=0; $i<$dimInterests;$i++)
- {
- $element["interests"][$i] = substr($element["interests"][$i], strpos($element["interests"][$i], "_")+1);
- }
- }
- $element["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($user["_id"]);
- $element["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($user, true);
- $element["user_type"] = ucfirst($user['type']);
- if (strcasecmp($user['type'], "personal") == 0)
- {
- $element["user_gender"] = ucfirst($user['gender']);
- }
- if(!is_null($viewerID))
- {
- $isFollowing = $userUtility->isFollowing($viewerID, $user["_id"]);
- $element["already_followed"] = $isFollowing ? "true" : "false";
- $element["can_send_message"] = ($isFollowing || $userUtility->isFollowing($user["_id"], $viewerID)) ? "true" : "false";
- }
- $userInfo[] = $element;
- }
- if(in_array(0, $arrayUserIDs))
- {
- array_push($userInfo, $this->buildDetedUser());
- }
- return $userInfo;
- }
- else
- {
- return array();
- }
- }
- /**
- * This method builds a deleted user.
- */
- private function buildDetedUser()
- {
- $userDeleted = array();
- $userDeleted["user_id"] = 0;
- $userDeleted["display_name"] = "Deleted User";
- $userDeleted["nickname"] = "Deleted User";
- $userDeleted["status"] = "";
- $userDeleted["qr_details"] = 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get ( 'Zend_View' )->baseUrl () ;
- $userDeleted["ranking"] = 0;
- $userDeleted["positions_ranking"] = 0;
- $userDeleted["interest"] = array();
- $userDeleted["cities"] = array();
- $userDeleted["photo_profile_url"] = "";
- $userDeleted["user_type"] = "Personal";
- $userDeleted["user_gender"] = "M";
- $userDeleted["already_followed"] = "false";
- $userDeleted["can_send_message"] = "false";
- return $userDeleted;
- }
- private function getUserTypeFieldValues($arrayFieldsValues){
- $userType = null;
- foreach ($arrayFieldsValues as $value) {
- if ($value["field_id"] == 1){
- $userType = ($value["value"] == 1) ? "Personal" : "Business";
- }
- }
- if (strcasecmp($userType,"Personal") == 0){
- foreach ($arrayFieldsValues as $value) {
- if ($value["field_id"] == 5){
- $userGender = $value["value"] == 2 ? "M" : "W";
- }
- if (isset($userGender))
- break;
- }
- }
- $element = array();
- $element["user_type"] = $userType;
- if (isset($userGender))
- $element["user_gender"] = $userGender;
- return $element;
- }
- /**
- * Get the user's friend in paginated way.
- *
- * @param $userID of the user who want to get the friends list.
- * @param $lastReceivedUserID
- * @return array representing the friends.
- */
- public function getSearchedUserFriends($userID, $search_string) {
- $limit = 20;
- $user = Engine_Api::_()->user()->getUser($userID);
- $membership = Engine_Api::_()->getDbtable('membership', 'user');
- $select = $user->membership()->getMembershipsOfSelect($user);
- /* Da completare */
- }
- /**
- * Get the user's friend that matches $valuetosearch. limit 20
- *
- * @param $userID of
- * the user who want to get the friends list.
- * @return array representing the friends.
- */
- public function getUserFriends($userID,$valueToSearch)
- {
- //la regex per cercare l'utente
- $searchRegex = new MongoRegex('/' . $valueToSearch . '/i');
- //ottengo sia i follower che i following dell'utente corrente
- $friendships = MyMongo_Connection::find(static::$followersColl,
- array(
- '$or' => array(
- array("follower" => $userID),
- array("following" => $userID)
- )
- ),
- array(
- "follower" => 1,
- "following" => 1
- )
- );
- //array che conterrà tutti gli id dei follower e following
- $friend_ids = array();
- foreach ($friendships as $fs)
- {
- if($fs['follower'] === $userID)
- {
- array_push($friend_ids, $fs['following']);
- }
- else if($fs['following'] === $userID)
- {
- array_push($friend_ids, $fs['follower']);
- }
- }
- //elimino i duplicati
- $friend_ids = array_unique($friend_ids);
- //riordino la numerazione dell'array
- $friend_ids = array_values($friend_ids);
- //cerco tra i follower/following coloro che corrispondono alla chiave di ricerca digitata (limite a 10)
- $friends_cursor = MyMongo_Connection::find(
- static::$usersCollection,
- array(
- "_id" => array('$in' => $friend_ids),
- "level" => 4,
- '$or' => array(
- array("username" => $searchRegex),
- array("name" => $searchRegex),
- array("surname" => $searchRegex),
- array("company" => $searchRegex)
- )
- ),
- array(),
- array(),
- 10
- );
- $followersFollowing = array();
- //serve per prevenire inserimento di doppioni
- $temp = array ();
- foreach ($friends_cursor as $currFriend)
- {
- if (!array_key_exists ( $currFriend ['username'], $temp ))
- {
- $temp [$currFriend ['username']] = 1;
- array_push($followersFollowing, $currFriend);
- }
- }
- $friends = $this->getUserDetailsToArray($followersFollowing);
- return $friends;
- }
- /**
- * This method returns the path of social matic application.
- * @return social matic full path
- */
- public function getSocialMaticPath()
- {
- $pathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
- return $this->getPropertyArray($pathConfFile)['socialmaticFullpath'];
- }
- /**
- * This function checks if a device_type is valid
- * @param $codeArray the array of valid codes
- * @param $device_type the code need to verify
- * @return boolean
- */
- public function checkAllowedDeviceType($codeArray, $device_type)
- {
- $found = false;
- foreach ($codeArray as $value) {
- if($value == $device_type)
- $found = true;
- }
- return $found;
- }
- /**
- * Questo metodo crea un array di tag facendo le verifiche/modifiche per ognuno
- * @param $freeTags
- * @return array di tag "puliti"
- */
- public function createTag($freeTags)
- {
- $arrayTags = explode(",",$freeTags);
- $arrayTags=$this->array_iunique($arrayTags);
- //check if there are tags
- if($dim=sizeof($arrayTags) > 0)
- {
- for($i = 0; $i < $dim; $i++)
- {
- $currTag = (strlen($arrayTags[$i]) > 30) ? mb_substr($arrayTags[$i], 0, 30, 'utf-8') : $arrayTags[$i];
- $currTag = htmlspecialchars($currTag,ENT_NOQUOTES);
- $arrayTags[$i] = $currTag;
- }
- }
- return $arrayTags;
- }
- /**
- * Fa l'array unique case insensitive
- * @param $array
- * @return multitype:
- */
- private function array_iunique($array) {
- return array_intersect_key(
- $array,
- array_unique(array_map("StrToLower",$array))
- );
- }
- /**
- * This method sets the default permission (friends of friends) to the album given in input
- * @param $album_id
- */
- public function setDefaultPermissionAlbum($album)
- {
- $auth = Engine_Api::_()->authorization()->context;
- //$roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
- $auth->setAllowed($album, 'owner', 'view', true);
- $auth->setAllowed($album, 'owner_member', 'view', true);
- $auth->setAllowed($album, 'owner_member_member', 'view', true);
- $auth->setAllowed($album, 'owner', 'comment', true);
- $auth->setAllowed($album, 'owner_member', 'comment', true);
- $auth->setAllowed($album, 'owner_member_member', 'comment', true);
- $auth->setAllowed($album, 'owner', 'tag', true);
- }
- /**
- * This method return photo's orientation: vertical or horizontal
- * @param unknown $filepath
- */
- public function getFileImageOrientation($filepath)
- {
- $image = Engine_Image::factory();
- $image->open($filepath);
- $orientation = "vertical";
- if($image->width > $image->height)
- {
- $orientation = "horizontal";
- }
- $image->destroy();
- return $orientation;
- }
- public function createPhotoRecord
- (
- $userID, $deviceID, $fullpathFile, $username, $extension,
- $compliantName,$fileSize, $description, $timestampID, $tagsArray, $coordinates, $creation_date
- )
- {
- $orientation = $this->getFileImageOrientation($fullpathFile);
- $imgInfos = $this->createFiles($extension, $compliantName);
- $_id = hash("md5", $description . $creation_date->__toString());
- $arrayValueToInsert = array
- (
- "_id" => $_id,
- "title" => $description,
- "timestamp_id" => $timestampID,
- "creation_date" => $creation_date,
- "modified_date" => $creation_date,
- "owner_id" => $userID,
- "owner_username" => $username,
- "fullsize_img" => $imgInfos['fullsize_img'],
- "thumb_img" => $imgInfos['thumb_img'],
- "img_orientation" => $orientation,
- "comments_count" => 0,
- "cools_count" => 0,
- "device_id" => $deviceID,
- "is_public" => true,
- "distance" => 0,
- "moves_count" => 0,
- "offers_count" => 0,
- "photosee_count" => 0,
- "deleted" => false
- );
- if(!is_null($coordinates))
- {
- $geoArray = $this->Get_Address_From_Google_Maps($coordinates['lat'], $coordinates['lon']);
- $city = (sizeof($geoArray) != 0) ? $geoArray["city"] : "NULL";
- $arrayValueToInsert["upload_position"] = array('lat'=>$coordinates['lat'], 'lon' => $coordinates['lon'], 'city' => $city);
- $arrayValueToInsert["position_uploader"] = $userID;
- //salva la mappa statica e ne ottiene l'url in cui è stata salvata
- $arrayValueToInsert["map_upload_img_url"] = Engine_Api::_()->getApi('googleutility', 'core')->saveStaticPhotoMap($coordinates['lat'], $coordinates['lon']);
- }
- if(!is_null($tagsArray))
- {
- $arrayValueToInsert["tags"] = $tagsArray;
- }
- MyMongo_Connection::addDocument(static::$photosColl, $arrayValueToInsert);
- return array("photoID" => $_id) ;
- }
- /**
- * Salva una immagine su s3 ed eventualmente anche il thumb se $noResize è false
- * @param $extension
- * @param $compliantName
- * @param $fileName
- * @param string $noResize
- * @return multitype:multitype:string unknown
- */
- public function createFiles($extension, $compliantName, $noResize = false)
- {
- //ottengo il path del file che contiene le proprietà relative ai paths
- $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
- $arrProp = $this->getPropertyArray($fullpathConfFile);
- //local path che sarà usato in amazon s3
- $storagePath = $arrProp['localPathImage'].$compliantName."_m.".$extension;
- //hash foto originale
- $hashOriginal = hash_file('md5', $arrProp['localPathImage'].$compliantName."_m.".$extension);
- //file size originale
- $originalFileSize = filesize($arrProp['localPathImage'].$compliantName."_m.".$extension);
- //salvo su amazon immagine dimensioni originali
- $this->uploadOnS3($arrProp['temporaryPath'].$compliantName."_m.".$extension, $storagePath);
- $toRet = array('fullsize_img' => array('url' => $storagePath,'hash' => $hashOriginal, 'size' => $originalFileSize));
- if(!$noResize)
- {
- //local path che sarà usato in amazon s3
- $storagePathThumb = $arrProp['localPathImage'].$compliantName."_in.".$extension;
- //hash foto thumbl
- $hashThumb = hash_file('md5', $arrProp['localPathImage'].$compliantName."_in.".$extension);
- //file size thumb
- $thumbFileSize = filesize($arrProp['localPathImage'].$compliantName."_in.".$extension);
- //salvo su amazon immagine thumb
- $this->uploadOnS3($arrProp['temporaryPath'].$compliantName."_in.".$extension, $storagePathThumb);
- $toRet['thumb_img'] = array('url' => $storagePathThumb, 'hash' => $hashThumb, 'size' => $thumbFileSize);
- }
- return $toRet;
- }
- /**
- * Effettua l'upload di una foto su s3.
- * @param $filepath
- * @param $filepathToSaveInS3
- * @return path relativo salvato su amazonS3|NULL
- */
- public function uploadOnS3($filepath, $filepathToSaveInS3)
- {
- $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
- if ($s3->putObjectFile($filepath, bucket, $filepathToSaveInS3, s3upload_S3::ACL_PUBLIC_READ))
- {
- @unlink($filepath);
- return $final_img_name;
- }
- else
- {
- @unlink($filepath);
- Utilities_Static::log("ERROR while uploading file: " . $img_full_name);
- return null;
- }
- }
- /**
- * This method read a conf file ini and return an array
- * key-value.
- * @param $fullpathIniFile
- * @return multitype:
- */
- public function getPropertyArray($fullpathIniFile)
- {
- return parse_ini_file($fullpathIniFile);
- }
- /**
- * This method create a single file from a base64 string.
- * @param $byte base64 string
- * @param $pathToSave path to save the file
- * @param $imgName image's name
- * @return array containing the extension and size of created file.
- */
- public function createFileFromBase64String($byte, $pathToSave, $filename)
- {
- //decode the base64
- $isOK = $decodedData=base64_decode($byte, true);
- if($isOK) {
- //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
- $mime_arr = $this->getFileMIME($decodedData);
- $fullpathFile=$pathToSave.$filename;
- @file_put_contents( $fullpathFile."_m.".$mime_arr[1], $decodedData );
- chmod($fullpathFile."_m.".$mime_arr[1], 0777);
- return array("extension" => $mime_arr[1], "filesize" => strlen($decodedData));
- }
- return null;
- }
- /**
- * This method create a image from a base64 string and save it
- * in the specified path.
- * @param $byte the BASE64 string
- * @param $pathToSave path to save image
- * @param $imgName the image's name
- * @return file info created
- */
- public function createImageFromBase64String($byte, $pathToSave, $imgName)
- {
- //decode the base64
- $decodedImage=base64_decode($byte);
- //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
- $mime_arr = $this->getFileMIME($decodedImage);
- //create one photo resized
- $this->resizeAndCreatePhoto($decodedImage, $pathToSave, $imgName, $mime_arr[1] );
- return array("extension" => $mime_arr[1], "filesize" => strlen($decodedImage));
- }
- /**
- * This method create from a photo input a new photo resized.
- * @param $decodedData
- * @param $pathToSave
- * @param $imgName
- * @param $filetype
- */
- public function resizeAndCreatePhoto($decodedData, $pathToSave, $imgName, $filetype) {
- $fullpathFile = $pathToSave . $imgName;
- $main_photo_full_path = $fullpathFile . "_m." . $filetype;
- @file_put_contents($main_photo_full_path, $decodedData);
- chmod($main_photo_full_path, 0777);
- $name = basename($fullpathFile);
- $path = dirname($fullpathFile);
- $image = Engine_Image::factory();
- $image->open($main_photo_full_path);
- // Create resized image
- $iMainPath = $path . '/' . $name . "_in." . $filetype;
- if($image->width > $image->height) {
- $image->resize(381, 254)->write($iMainPath)->destroy();
- } else {
- $image->resize(254, 381)->write($iMainPath)->destroy();
- }
- chmod($iMainPath, 0777);
- if($filetype == "jpg" || $filetype == "jpeg") {
- $im = imagecreatefromjpeg($main_photo_full_path);
- imageinterlace($im , true);
- imagejpeg($im , $main_photo_full_path, 100);
- $im = imagecreatefromjpeg($iMainPath);
- imageinterlace($im , true);
- imagejpeg($im , $iMainPath, 100);
- imagedestroy($im);
- }
- $image->destroy();
- }
- /**
- * This method return the file's MIME Type (array[0] -> mime_major, array[1] -> mime_minor) given in input (e.g. image/jpeg)
- * @param $base64Decoded
- */
- public function getFileMIME($base64Decoded)
- {
- $f = finfo_open();
- return explode("/",finfo_buffer($f, $base64Decoded, FILEINFO_MIME_TYPE));
- }
- /**
- * Aggiunge un item al feed del creatore dell'item ed a tutti i suoi follower
- * @param $userID
- * @param $type
- * @param $idItem
- */
- public function addActivity($userID, $type, $idItem, $creation_date = null) {
- if($creation_date == null) {
- $now = new MongoDate();
- } else {
- $now = $creation_date;
- }
- $flowItem = array('item_id'=>$idItem,'item_type'=>$type,'poster_id'=>$userID,'post_date'=>$now);
- //aggiungo nel flow del poster
- MyMongo_Connection::addInFeed($userID, array($flowItem), 128);
- //oggetto utente
- $userObj = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $userID));
- //se è pubblico l'utente allora si aggiunge la foto creata nei post dei suoi follower
- if($userObj->is_public)
- {
- /*
- * Aggiungo a tutti i follower il post creato mediante task temporizzato: INIZIO
- */
- $followersIDsArr = array();
- $cursor = MyMongo_Connection::find(static::$followersColl, array('following' => $userID));
- foreach ($cursor as $curr)
- {
- array_push($followersIDsArr, $curr['follower']);
- }
- //se l'utente ha followers
- if(sizeof($followersIDsArr) > 0)
- {
- //aggiungo il document che sarà letto dal task di aggiornamento
- MyMongo_Connection::addDocument(static::$photosTaskColl, array(
- 'photo_id' => $idItem,
- 'owner_id' => $userID,
- 'taskcreation_date' => $now,
- 'remaining_users' => $followersIDsArr,
- 'active' => true
- ));
- }
- /*
- * Aggiungo a tutti i follower il post creato mediante task temporizzato: FINE
- */
- }
- //aggiungo il post nella collection generale dei post
- MyMongo_Connection::addDocument(static::$postsColl, $flowItem);
- }
- /* OLD METHOD */
- /**
- * This method generate a full deviceID for a socialmatic device
- * @param $partialDeviceID
- * @return string
- */
- public function otherDeviceIdGenerator($partialDeviceID)
- {
- $realAlphaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[0]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[1]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[2]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[3]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[4]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[5]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[6]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[7])
- ) % 9;
- $realBetaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[9]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[10]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[11]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[12]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[14]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[15]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[16]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[17])
- ) % 9;
- $realGammaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[19]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[20]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[21]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[22])
- ) % 9;
- $realDeltaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[24]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[25]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[26]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[27]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[28]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[29]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[30]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[31]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[32]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[33]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[34]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[35])
- ) % 9;
- return $partialDeviceID."-".$realAlphaChar.$realBetaChar.$realGammaChar.$realDeltaChar;
- }
- /**
- * This method check if the deviceID given in input is valid for a socialmatic device
- * @param $deviceID
- * @return boolean
- */
- public function checkOtherDeviceIDCorrectness($deviceID)
- {
- //check pattern deviceID
- $pattern = "/^[A-Z0-9]{8}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{12}[-]{1}[A-Z0-9]{4}$/";
- if(preg_match($pattern,$deviceID) == 0)
- {
- return false;
- }
- else
- {
- $alphaChar = $deviceID[37];
- $betaChar = $deviceID[38];
- $gammaChar = $deviceID[39];
- $deltaChar = $deviceID[40];
- $realAlphaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[0]) +
- $this->decimalConversionIfNotANumber($deviceID[1]) +
- $this->decimalConversionIfNotANumber($deviceID[2]) +
- $this->decimalConversionIfNotANumber($deviceID[3]) +
- $this->decimalConversionIfNotANumber($deviceID[4]) +
- $this->decimalConversionIfNotANumber($deviceID[5]) +
- $this->decimalConversionIfNotANumber($deviceID[6]) +
- $this->decimalConversionIfNotANumber($deviceID[7])
- ) % 9;
- $realBetaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[9]) +
- $this->decimalConversionIfNotANumber($deviceID[10]) +
- $this->decimalConversionIfNotANumber($deviceID[11]) +
- $this->decimalConversionIfNotANumber($deviceID[12]) +
- $this->decimalConversionIfNotANumber($deviceID[14]) +
- $this->decimalConversionIfNotANumber($deviceID[15]) +
- $this->decimalConversionIfNotANumber($deviceID[16]) +
- $this->decimalConversionIfNotANumber($deviceID[17])
- ) % 9;
- $realGammaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[19]) +
- $this->decimalConversionIfNotANumber($deviceID[20]) +
- $this->decimalConversionIfNotANumber($deviceID[21]) +
- $this->decimalConversionIfNotANumber($deviceID[22])
- ) % 9;
- $realDeltaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[24]) +
- $this->decimalConversionIfNotANumber($deviceID[25]) +
- $this->decimalConversionIfNotANumber($deviceID[26]) +
- $this->decimalConversionIfNotANumber($deviceID[27]) +
- $this->decimalConversionIfNotANumber($deviceID[28]) +
- $this->decimalConversionIfNotANumber($deviceID[29]) +
- $this->decimalConversionIfNotANumber($deviceID[30]) +
- $this->decimalConversionIfNotANumber($deviceID[31]) +
- $this->decimalConversionIfNotANumber($deviceID[32]) +
- $this->decimalConversionIfNotANumber($deviceID[33]) +
- $this->decimalConversionIfNotANumber($deviceID[34]) +
- $this->decimalConversionIfNotANumber($deviceID[35])
- ) % 9;
- if (
- (($alphaChar==$realAlphaChar)) &&
- (($betaChar==$realBetaChar) ) &&
- (($gammaChar==$realGammaChar) ) &&
- (($deltaChar==$realDeltaChar) )
- )
- {
- //the deviceID is valid
- return true;
- }
- else return false;
- }
- }
- /**
- * This method generate a full deviceID for a socialmatic device
- * @param $partialDeviceID
- * @return string
- */
- public function socialMaticDeviceIdGenerator($partialDeviceID)
- {
- $realAlphaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[0]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[10]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[14]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[26])
- ) % 9;
- $realBetaChar =
- (
- $this->decimalConversionIfNotANumber($partialDeviceID[11]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[15]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[19]) +
- $this->decimalConversionIfNotANumber($partialDeviceID[25])
- ) % 9;
- $realGammaChar = (($realAlphaChar + $realBetaChar)/9) % 9;
- $realDeltaChar = ( ($realGammaChar + $realAlphaChar) * ($realGammaChar + $realBetaChar) ) % 5 ;
- return $partialDeviceID."-".$realAlphaChar.$realBetaChar.$realGammaChar.$realDeltaChar;
- }
- /**
- * Verifica se l'utente specificato possiede un dispositivo di tipo socialmatic camera
- * @param $user (array o oggetto rappresentante un utente)
- */
- public function checkIfUserHasASocialmaticCamera($user)
- {
- if(is_object($user))
- {
- $user = (array)$user;
- }
- else if(!is_array($user))
- {
- return true; //errore
- }
- return $this->checkIfThereIsASMCamera($user['devices']);
- }
- /**
- * Verifica se nell'array di device ce n'è uno che è di tipo socialmatic camera.
- * @param $devicesArr
- * @return boolean
- */
- public function checkIfThereIsASMCamera($devicesArr)
- {
- $hasSocialmaticCamera = false;
- //scandisco tutti i device
- foreach ($devicesArr as $currDevice)
- {
- //se il device corrente è di tipo socialmatic
- if($this->checkSocialMaticDeviceIDCorrectness($currDevice['id']))
- {
- $hasSocialmaticCamera = true;
- break;
- }
- }
- return $hasSocialmaticCamera;
- }
- /**
- * This method check if the deviceID given in input is valid for a socialmatic device
- * @param $deviceID
- * @return boolean
- */
- public function checkSocialMaticDeviceIDCorrectness($deviceID)
- {
- //check pattern deviceID
- $pattern = "/^[A-Z0-9]{8}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{4}[-]{1}[A-Z0-9]{12}[-]{1}[A-Z0-9]{4}$/";
- if(preg_match($pattern,$deviceID) == 0)
- {
- return FALSE;
- }
- else
- {
- $alphaChar = $deviceID[37];
- $betaChar = $deviceID[38];
- $gammaChar = $deviceID[39];
- $deltaChar = $deviceID[40];
- $realAlphaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[0]) +
- $this->decimalConversionIfNotANumber($deviceID[10]) +
- $this->decimalConversionIfNotANumber($deviceID[14]) +
- $this->decimalConversionIfNotANumber($deviceID[26])
- ) % 9;
- $realBetaChar =
- (
- $this->decimalConversionIfNotANumber($deviceID[11]) +
- $this->decimalConversionIfNotANumber($deviceID[15]) +
- $this->decimalConversionIfNotANumber($deviceID[19]) +
- $this->decimalConversionIfNotANumber($deviceID[25])
- ) % 9;
- $realGammaChar = (($realAlphaChar + $realBetaChar)/9) % 9;
- $realDeltaChar = ( ($realGammaChar + $realAlphaChar) * ($realGammaChar + $realBetaChar) ) % 5 ;
- if (
- (($alphaChar==$realAlphaChar)) &&
- (($betaChar==$realBetaChar) ) &&
- (($gammaChar==$realGammaChar) ) &&
- (($deltaChar==$realDeltaChar) )
- )
- {
- //the deviceID is valid
- return TRUE;
- }
- else return FALSE;
- }
- }
- /**
- * This method convert the char given in input into matched decimal ASCII. Whether input
- * is a number will be not converted.
- * @param $char
- * @return decimal representation of $char.
- */
- public function decimalConversionIfNotANumber($char)
- {
- $dec=0;
- if(!is_numeric($char))
- {
- $dec = $this->ascii_to_dec($char)[0];
- }
- else $dec = $char;
- return $dec;
- }
- /**
- * This method convert a string in respectively decimal ascii for each char
- * @param $str
- * @return number
- */
- public function ascii_to_dec($str)
- {
- for ($i = 0, $j = strlen($str); $i < $j; $i++) {
- $dec_array[] = ord($str{$i});
- }
- return $dec_array;
- }
- /**
- * This method create an authtoken
- * @return string
- */
- public function getAuthToken() {
- $charid = strtoupper(md5(uniqid(rand(), true)));
- $auth_token = substr($charid, 0, 8) . '-' .
- substr($charid, 8, 8) . '-' .
- substr($charid, 16, 8) . '-' .
- substr($charid, 24, 8);
- return $auth_token;
- }
- public function myGetTimeZone($differenceFromGreenwich)
- {
- $timezones = array(
- '-11:00'=>'Pacific/Midway',
- '-11:00'=>'US/Samoa',
- '-10:00'=>'US/Hawaii',
- '-09:00'=>'US/Alaska',
- '-08:00'=>'US/Pacific',
- '-08:00'=>'America/Tijuana',
- '-07:00'=>'US/Arizona',
- '-07:00'=>'US/Mountain',
- '-07:00'=>'America/Chihuahua',
- '-07:00'=>'America/Mazatlan',
- '-06:00'=>'America/Mexico_City',
- '-06:00'=>'America/Monterrey',
- '-06:00'=>'Canada/Saskatchewan',
- '-06:00'=>'US/Central',
- '-05:00'=>'US/Eastern',
- '-05:00'=>'US/East-Indiana',
- '-05:00'=>'America/Bogota',
- '-05:00'=>'America/Lima',
- '-04:30'=>'America/Caracas',
- '-04:00'=>'Canada/Atlantic',
- '-04:00'=>'America/La_Paz',
- '-04:00'=>'America/Santiago',
- '-03:30'=>'Canada/Newfoundland',
- '-03:00'=>'America/Buenos_Aires',
- '-03:00'=>'Greenland',
- '-02:00'=>'Atlantic/Stanley',
- '-01:00'=>'Atlantic/Azores',
- '-01:00'=>'Atlantic/Cape_Verde',
- '+00:00'=>'Africa/Casablanca',
- '+00:00'=>'Europe/Dublin',
- '+00:00'=>'Europe/Lisbon',
- '+00:00'=>'Europe/London',
- '+00:00'=>'Africa/Monrovia',
- '+01:00'=>'Europe/Amsterdam',
- '+01:00'=>'Europe/Belgrade',
- '+01:00'=>'Europe/Berlin',
- '+01:00'=>'Europe/Bratislava',
- '+01:00'=>'Europe/Brussels',
- '+01:00'=>'Europe/Budapest',
- '+01:00'=>'Europe/Copenhagen',
- '+01:00'=>'Europe/Ljubljana',
- '+01:00'=>'Europe/Madrid',
- '+01:00'=>'Europe/Paris',
- '+01:00'=>'Europe/Prague',
- '+01:00'=>'Europe/Rome',
- '+01:00'=>'Europe/Sarajevo',
- '+01:00'=>'Europe/Skopje',
- '+01:00'=>'Europe/Stockholm',
- '+01:00'=>'Europe/Vienna',
- '+01:00'=>'Europe/Warsaw',
- '+01:00'=>'Europe/Zagreb',
- '+02:00'=>'Europe/Athens',
- '+02:00'=>'Europe/Bucharest',
- '+02:00'=>'Africa/Cairo',
- '+02:00'=>'Africa/Harare',
- '+02:00'=>'Europe/Helsinki',
- '+02:00'=>'Europe/Istanbul',
- '+02:00'=>'Asia/Jerusalem',
- '+02:00'=>'Europe/Kiev',
- '+02:00'=>'Europe/Minsk',
- '+02:00'=>'Europe/Riga',
- '+02:00'=>'Europe/Sofia',
- '+02:00'=>'Europe/Tallinn',
- '+02:00'=>'Europe/Vilnius',
- '+03:00'=>'Asia/Baghdad',
- '+03:00'=>'Asia/Kuwait',
- '+03:00'=>'Africa/Nairobi',
- '+03:00'=>'Asia/Riyadh',
- '+03:00'=>'Asia/Tehran',
- '+04:00'=>'Europe/Moscow',
- '+04:00'=>'Asia/Baku',
- '+04:00'=>'Europe/Volgograd',
- '+04:00'=>'Asia/Muscat',
- '+04:00'=>'Asia/Tbilisi',
- '+04:00'=>'Asia/Yerevan',
- '+04:30'=>'Asia/Kabul',
- '+05:00'=>'Asia/Karachi',
- '+05:00'=>'Asia/Tashkent',
- '+05:30'=>'Asia/Kolkata',
- '+05:45'=>'Asia/Kathmandu',
- '+06:00'=>'Asia/Yekaterinburg',
- '+06:00'=>'Asia/Almaty',
- '+06:00'=>'Asia/Dhaka',
- '+07:00'=>'Asia/Novosibirsk',
- '+07:00'=>'Asia/Bangkok',
- '+07:00'=>'Asia/Jakarta',
- '+08:00'=>'Asia/Krasnoyarsk',
- '+08:00'=>'Asia/Chongqing',
- '+08:00'=>'Asia/Hong_Kong',
- '+08:00'=>'Asia/Kuala_Lumpur',
- '+08:00'=>'Australia/Perth',
- '+08:00'=>'Asia/Singapore',
- '+08:00'=>'Asia/Taipei',
- '+08:00'=>'Asia/Ulaanbaatar',
- '+08:00'=>'Asia/Urumqi',
- '+09:00'=>'Asia/Irkutsk',
- '+09:00'=>'Asia/Seoul',
- '+09:00'=>'Asia/Tokyo',
- '+09:30'=>'Australia/Adelaide',
- '+09:30'=>'Australia/Darwin',
- '+10:00'=>'Asia/Yakutsk',
- '+10:00'=>'Australia/Brisbane',
- '+10:00'=>'Australia/Canberra',
- '+10:00'=>'Pacific/Guam',
- '+10:00'=>'Australia/Hobart',
- '+10:00'=>'Australia/Melbourne',
- '+10:00'=>'Pacific/Port_Moresby',
- '+10:00'=>'Australia/Sydney',
- '+11:00'=>'Asia/Vladivostok',
- '+12:00'=>'Asia/Magadan',
- '+12:00'=>'Pacific/Auckland',
- '+12:00'=>'Pacific/Fiji'
- );
- return $timezones[$differenceFromGreenwich];
- }
- /**************************************** SECTION REFERS GOOGLE MAPS API: BEGIN ********************************/
- /*
- * Given longitude and latitude in North America, return the address using The Google Geocoding API V3
- *
- */
- /**
- * This method returns an array representing information about latitude and longitude given in input.
- * @param $lat
- * @param $lon
- * @return information array about latitude and longitude.
- */
- public function Get_Address_From_Google_Maps($lat, $lon) {
- $url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
- $googleUtility = Engine_Api::_()->getApi("googleutility","core");
- $url = $googleUtility->getSMSignedURL($url,false);
- /*$log = Zend_Registry::get('Zend_Log');
- $log->log("**********".$url."************".$query, Zend_Log::CRIT);*/
- // Make the HTTP request
- $data = @file_get_contents($url);
- // Parse the json response
- $jsondata = json_decode($data,true);
- // If the json data is invalid, return empty array
- if (!$this->check_status($jsondata)) return array();
- $address = array(
- 'country' => $this->google_getCountry($jsondata),
- 'province' => $this->google_getProvince($jsondata),
- 'city' => $this->google_getCity($jsondata),
- 'street' => $this->google_getStreet($jsondata),
- 'postal_code' => $this->google_getPostalCode($jsondata),
- 'country_code' => $this->google_getCountryCode($jsondata),
- 'formatted_address' => $this->google_getAddress($jsondata),
- );
- return $address;
- }
- /*
- * Check if the json data from Google Geo is valid
- */
- public function check_status($jsondata) {
- if ($jsondata["status"] == "OK") return true;
- return false;
- }
- /*
- * Given Google Geocode json, return the value in the specified element of the array
- */
- public function google_getCountry($jsondata) {
- return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
- }
- public function google_getProvince($jsondata) {
- return $this->Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
- }
- /* OLD */
- /*
- public function google_getCity($jsondata) {
- return $this->Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
- }*/
- public function google_getCity($jsondata) {
- $city = $this->Find_Long_Name_Given_Type("sublocality", $jsondata["results"][0]["address_components"]);
- if(empty($city))
- {
- $city = $this->Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
- if(empty($city))
- {
- $city = $this->Find_Long_Name_Given_Type("administrative_area_level_3", $jsondata["results"][0]["address_components"], true);
- if(empty($city))
- {
- $city = $this->Find_Long_Name_Given_Type("administrative_area_level_2", $jsondata["results"][0]["address_components"], true);
- if(empty($city))
- {
- $city = $this->Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
- }
- }
- }
- }
- return $city;
- }
- public function google_getStreet($jsondata) {
- return $this->Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . $this->Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
- }
- public function google_getPostalCode($jsondata) {
- return $this->Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
- }
- public function google_getCountryCode($jsondata) {
- return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
- }
- public function google_getAddress($jsondata) {
- return $jsondata["results"][0]["formatted_address"];
- }
- /*
- * Searching in Google Geo json, return the long name given the type.
- * (If long_name is true, return short name)
- */
- public function Find_Long_Name_Given_Type($type, $array, $long_name = false) {
- foreach( $array as $value) {
- if (in_array($type, $value["types"])) {
- return $value["long_name"];
- }
- }
- }
- /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
- /*:: :*/
- /*:: This routine calculates the distance between two points (given the :*/
- /*:: latitude/longitude of those points). It is being used to calculate :*/
- /*:: the distance between two locations using GeoDataSource(TM) Products :*/
- /*:: :*/
- /*:: Definitions: :*/
- /*:: South latitudes are negative, east longitudes are positive :*/
- /*:: :*/
- /*:: Passed to function: :*/
- /*:: lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :*/
- /*:: lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :*/
- /*:: unit = the unit you desire for results :*/
- /*:: where: 'M' is statute miles :*/
- /*:: 'K' is kilometers (default) :*/
- /*:: 'N' is nautical miles :*/
- /*:: Worldwide cities and other features databases with latitude longitude :*/
- /*:: are available at http://www.geodatasource.com :*/
- /*:: :*/
- /*:: For enquiries, please contact sales@geodatasource.com :*/
- /*:: :*/
- /*:: Official Web site: http://www.geodatasource.com :*/
- /*:: :*/
- /*:: GeoDataSource.com (C) All Rights Reserved 2013 :*/
- /*:: :*/
- /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
- public function distance($lat1, $lon1, $lat2, $lon2, $unit) {
- $theta = (float)$lon1 - (float)$lon2;
- $dist = sin(deg2rad((float)$lat1)) * sin(deg2rad((float)$lat2)) + cos(deg2rad((float)$lat1)) * cos(deg2rad((float)$lat2)) * cos(deg2rad($theta));
- $dist = acos($dist);
- $dist = rad2deg($dist);
- $miles = $dist * 60 * 1.1515;
- $unit = strtoupper($unit);
- if ($unit == "K") {
- return ($miles * 1.609344);
- } else if ($unit == "M") {
- return ($miles * 0.8684);
- } else {
- return $miles;
- }
- }
- /**************************************** SECTION REFERS GOOGLE MAPS API: END ********************************/
- public function base64_encode_image ($filename) {
- if ($filename) {
- $imgbinary = fread(fopen($filename, "r"), filesize($filename));
- return base64_encode($imgbinary);
- }
- }
- /***RELEASE 2************************************************************/
- /**
- * method which returns information of user in input
- * @param $user who want to get the friends list.
- * @return array representing user information
- */
- public function getUserInfo($user, $requestUserID) {
- if(!is_object($user)) {
- $user = (object) $user;
- }
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $photoUtility = Engine_Api::_()->getApi('photoutility','core');
- $citiesAndMiles = $this->getAllCitiesAndTotalMiles($user->_id, $photoUtility);
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $gr_details = 'https://' . $_SERVER['HTTP_HOST'] . $appName . "profile/" . $user->username;
- $interests = array();
- foreach ($user->interests as $int) {
- $interest = array(
- "interest_id" => $int,
- "content" => $int
- );
- array_push($interests, $interest);
- }
- $canSendMessage = $userUtility->checkFriendshipChannelBetweenTwoUsers($user->_id,$requestUserID) ? "true" : "false";
- $membershipTable = Engine_Api::_()->getDbTable('membership','user');
- $alreadyFollowed = $userUtility->isFollowing($requestUserID, $user->_id) ? "true" : "false";
- if (strcasecmp ( $user->type, "Business" ) == 0) {
- $info = array (
- 'user_id' => $user->_id,
- 'email' => $user->email,
- 'nickname' => $user->username,
- 'name' => $user->name,
- 'surname' => $user->surname,
- 'status_msg' => $user->status,
- 'account_type' => ucfirst($user->type),
- 'company_name' => $user->company,
- 'country' => $user->country,
- 'vat' => $user->vat,
- 'professional_work_fld' => $user->workfield,
- 'location' => $user->location,
- 'cities' => array_values($citiesAndMiles['cities']),
- 'is_authentic' => $user->authentic ? "1" : "0",
- 'rank' => $this->getSocialmaticRanking($user),
- 'miles' => $citiesAndMiles['miles'],
- 'profile_photo_url' => isset($user->cropped_profilephoto_url) ? SM_BUCKET . $user->cropped_profilephoto_url : "",
- 'qr_details' => $gr_details,
- 'flow_photo_url' => isset($user->cropped_flowphoto_url) ? SM_BUCKET . $user->cropped_flowphoto_url : "",
- 'user_interests' => $interests,
- 'following_number' => $user->following_count,
- 'follower_number' => $user->followers_count,
- 'can_send_message' => $canSendMessage,
- 'already_followed' => $alreadyFollowed,
- 'is_public' => $user->is_public
- );
- } else {
- $info = array (
- 'user_id' => $user->_id,
- 'email' => $user->email,
- 'nickname' => $user->username,
- 'name' => $user->name,
- 'surname' => $user->surname,
- 'status_msg' => $user->status,
- 'account_type' => ucfirst($user->type),
- 'birthday' => $user->birthdate->sec,
- 'gender' => ucfirst($user->gender),
- 'location' => $user->location,
- 'cities' => array_values($citiesAndMiles['cities']),
- 'rank' => $this->getSocialmaticRanking($user),
- 'miles' => $citiesAndMiles['miles'],
- 'is_authentic' => $user->authentic ? "1" : "0",
- 'profile_photo_url' => isset($user->cropped_profilephoto_url) ? SM_BUCKET . $user->cropped_profilephoto_url : "",
- 'qr_details' => $gr_details,
- 'flow_photo_url' => isset($user->cropped_flowphoto_url) ? SM_BUCKET . $user->cropped_flowphoto_url : "",
- 'user_interests' => $interests,
- 'following_number' => $user->following_count,
- 'follower_number' => $user->followers_count,
- 'can_send_message' => $canSendMessage,
- 'already_followed' => $alreadyFollowed,
- 'is_public' => $user->is_public
- );
- }
- return $info;
- }
- private function getAllCitiesAndTotalMiles($userID, $photoUtility) {
- // get all photo records
- $allPhotoRecords = $photoUtility->getAlbumPhotos($userID);
- $citiesArray = array();
- $milesArray = array();
- $i = 0;
- foreach($allPhotoRecords as $currPhotoRecord) {
- // if the first photo's coordinates (upload coordinates or first photo see coordinates) isn't null
- if (!$currPhotoRecord['deleted'] && !is_null($photoUtility->getCoordinates($currPhotoRecord['_id']))) {
- $milesArray[$i] = (int) $photoUtility->getPhotoMiles($currPhotoRecord['_id']);
- $citiesArray[$i] = $photoUtility->getPhotoCities($currPhotoRecord['_id'], 1)[0]['city'];
- $i ++;
- }
- }
- return $i == 0 ? null : array (
- "cities" => array_unique($citiesArray),
- "miles" => array_sum($milesArray)
- );
- }
- /**
- * method which returns the album's photos of a registered user
- * @param $albumOwnerID userID owner or object owner of album
- * @return array representing album's photos:
- */
- public function getAlbum($userID, $albumOwnerID, $lastReceivedID,$numOfPhoto) {
- $albumOwner = null;
- if(is_object($albumOwnerID) || is_array($albumOwnerID)) {
- $albumOwner = (object) $albumOwnerID;
- $albumOwnerID = $albumOwner->_id;
- }
- $photoUtility = Engine_Api::_()->getApi('photoutility','core');
- // it get the reference to the table engine4_album_photos
- if (strcasecmp($userID, $albumOwnerID) != 0)
- $resultAlbumOwnerID = $photoUtility->getAlbumPhotos($albumOwnerID, null, null, $lastReceivedID, $numOfPhoto, true);
- else
- $resultAlbumOwnerID = $photoUtility->getAlbumPhotos($albumOwnerID, null, null, $lastReceivedID, $numOfPhoto, false);
- $album = array();
- $i = 0;
- foreach ($resultAlbumOwnerID as $photo) {
- $photo_id = $photo["_id"];
- $upload_date = $photo['creation_date']->sec;
- $arrayCities = $photoUtility->getPhotoCities($photo);
- $uploadCity = $arrayCities[0]["city"];
- $photoURLThumb = SM_BUCKET . $photo['thumb_img']['url'];
- $photoURL = SM_BUCKET . $photo['fullsize_img']['url'];
- $fileID = $photoFileRecord ["file_id"];
- $photoTags = $photoUtility->getPhotoTags ($photo);
- if($photoTags == null) {
- $photoTags = array();
- }
- $appName = Zend_Registry::get ( 'Zend_View' )->baseUrl () . "/";
- $textUtility = Engine_Api::_()->getApi('textutility', 'core');
- $qrDetails = 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "user/photodetail/view?p=" . $photo_id;
- $photoArray = array (
- 'photo_id' => $photo_id,
- 'photo_description' => $photo['title'],
- 'photo_see_counter' => $photo['photosee_count'],
- 'photo_tags' => $photoTags,
- 'photo_miles' => round($photo['distance'],2),
- 'photo_cools_number' => $photo['cools_count'],
- 'photo_movers_counter' => $photo['moves_count'],
- 'upload_city' => $uploadCity,
- 'upload_date' => $upload_date,
- 'map_upload_img_url' => SM_BUCKET . $photo['map_upload_img_url'],
- 'photo_url_thumb' => $photoURLThumb,
- 'photo_url' => $photoURL,
- "pin_counter" => isset($photo['upload_position']) ? $photo['moves_count'] + 1 : 0,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $photo['img_orientation'],
- 'comment_counter' => $photo['comments_count']
- );
- $album [$i] = $photoArray;
- $i ++;
- }
- if($albumOwner == null) {
- return array(
- 'photos' => $album,
- 'owner' => $this->getUserDetails($albumOwnerID)
- );
- } else {
- $owner = array(
- 'user_id' => $albumOwner->_id,
- 'nickname' => $albumOwner->username,
- 'status' => $albumOwner->status,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . Zend_Registry::get('Zend_View')->baseUrl() . "/" . "profile/" . $albumOwner->username,
- 'ranking' => $albumOwner->current_rank,
- 'positions_ranking' => $albumOwner->current_rank - $albumOwner->previous_rank,
- );
- $interests = array();
- foreach ($albumOwner->interests as $int) {
- $interest = explode("_", $int)[1];
- array_push($interests, $interest);
- }
- $owner["interests"] = $interests;
- $owner["user_cities"] = Utilities_Static::getPhotoutility()->getUploadCitiesForUser($albumOwner->_id);
- $owner["photo_profile_url"] = Utilities_Static::getProfilePhotoURL($albumOwner);
- $owner["user_type"] = ucfirst($albumOwner->type);
- if (isset($albumOwner->gender)) {
- $owner["user_gender"] = ucfirst($albumOwner->gender);
- }
- return array(
- 'photos' => $album,
- 'owner' => $owner
- );
- }
- }
- /**
- * add comment for specified photo
- * @param $objectID as a photo
- * @param $objectType as a type of object
- * @param $userID user of author post
- * @param $comment text comment
- * @return if response code is 200 returns json string format as {"Response":"Request OK"}
- */
- public function postComment($objectID, $objectType, $owner_id, $userID, $comment)
- {
- $viewer = MyMongo_Connection::findOne("users", array("_id" => $userID));
- $comment = htmlspecialchars($comment,ENT_NOQUOTES);
- $commentUtility = Engine_Api::_ ()->getApi ( "commentutility", "core" );
- $hashtagUtility = Engine_Api::_ ()->getApi ( "hashtagutility", "core" );
- $hashtagArray = $hashtagUtility->replaceHashTag($comment);
- $arrayUserMention = $hashtagUtility->replaceMention($comment);
- foreach (array_keys($arrayUserMention, $viewer->username) as $key) {
- unset($arrayUserMention[$key]);
- }
- $collection_name = Engine_Api::_()->getApi("coolutility", "core")->getItemCollection($objectType);
- $comment_id = null;
- $mentioned = null;
- if (strcasecmp($objectType, 'photo') == 0 || strcasecmp($objectType, 'offer') == 0 || strcasecmp($objectType, 'event') == 0)
- {
- /* Add new comment */
- $creation_date = new MongoDate();
- $_id = hash("md5", $userID. $objectID . $objectType . $creation_date->__toString());
- $params = array();
- $params['_id'] = $_id;
- $params['object_type'] = $objectType;
- $params['object_id'] = $objectID;
- $params['poster_id'] = $userID;
- $params['body'] = $comment;
- $params['creation_date'] = $creation_date;
- MyMongo_Connection::addDocument("comments", $params);
- /* Update "comments_count" in photo */
- //MyMongo_Connection::updateAndOrIncCollectionFields($collection_name, array("_id" => $objectID), array(), array("comments_count" => 1));
- $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("comments_count" => 1)), array("comments_count" => 1));
- /* Add Notifications */
- $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
- $object = new stdClass();
- $object->_id = $objectID;
- if($owner_id !== $userID)
- {
- $notifyApi->addNotification($owner_id, $viewer, $object, $objectType, 'commented', array('label' => $objectType));
- }
- //ottengo tutti gli userID degli utenti che hanno commentato l'oggetto corrente
- $arrayUserID = $commentUtility->getAllCommentUsers($objectType, $objectID);
- $pushUserIDs = array(); //conterrà tutti gli utenti a cui inviare la push notification
- foreach($arrayUserID as $userToNotification)
- {
- if (($userToNotification !== $owner_id) && ($userToNotification !== $userID))
- {
- $notifyApi->addNotificationExceptPushNotification($userToNotification, $viewer, $object, $objectType, 'commented_commented', array (
- 'label' => $objectType
- ));
- array_push($pushUserIDs, $userToNotification);
- }
- }
- //se ci sono utenti che hanno commentato
- if(sizeof($pushUserIDs) > 0)
- {
- //invio push notification agli utenti che hanno commentato l'oggetto corrente
- Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($pushUserIDs);
- }
- if(sizeof($arrayUserMention) == 1) {
- $mentioned = MyMongo_Connection::find("users", array("username" => $arrayUserMention[0]), array("_id" => 1));
- } else if(sizeof($arrayUserMention) > 1) {
- $mentioned = MyMongo_Connection::find("users", array("username" => array('$in' => $arrayUserMention)), array("_id" => 1));
- }
- $pushUserIDs = array(); //conterrà tutti gli utenti a cui inviare la push notification
- foreach ($mentioned as $userMention)
- {
- $notifyApi->addNotificationExceptPushNotification($userMention['_id'], $viewer, $object, $objectType, 'commented_mention', array(
- 'label' => $objectType
- ));
- array_push($pushUserIDs, $userMention['_id']);
- }
- //se ci sono utenti che hanno commentato
- if(sizeof($pushUserIDs) > 0)
- {
- //invio push notification agli utenti che hanno commentato l'oggetto corrente
- Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($pushUserIDs);
- }
- }
- $comment_id = $params['_id'];
- //aggiungi mapping utente menzionato - commento
- if($mentioned != null && $mentioned->count() > 0)
- {
- $commentUtility->addCommentMappingMentions($mentioned, $comment_id);
- }
- return array (
- 'Response' => 'Request OK' ,
- 'object_type' => Engine_Api::_()->getApi("activityutility","activity")->getOldTypesName($objectType)['object_type'],
- 'comment_id' => $comment_id,
- 'comment_count' => $result['comments_count'] + 1
- );
- }
- /**
- * returns all the available interests formatted as {{"interests_id":"1", "content":"music_rock"},...}
- */
- public function getAvailableInterests() {
- $interestsArray = array();
- $interests = MyMongo_Connection::find("interests");
- foreach ($interests as $int) {
- $interest = array(
- "interest_id" => $int['_id'],
- "content" => $int['_id']
- );
- array_push($interestsArray, $interest);
- }
- return $interestsArray;
- }
- /**
- * returns all the available professionale work field formatted as {{"interests_id":"16", "content":"Advertising"},...}
- */
- public function getAvailableWorkField(){
- $workfieldsArray = array();
- $workfields = MyMongo_Connection::find("workfields");
- foreach ($workfields as $wrk) {
- $workfield = array(
- "id" => $wrk['_id'],
- "text" => $wrk['_id']
- );
- array_push($workfieldsArray, $workfield);
- }
- return $workfieldsArray;
- }
- /**
- * make a COOL for a specified photo
- * @param $objectID as a object
- * @param $objectType as a type of object
- * @param $userID user of author COOL
- * @return if response code is 200 returns json string format as {"numOfCool":"13"}
- */
- public function makeCool($objectID, $objectType, $ownerID, $userID){
- $coolUtility = Engine_Api::_()->getApi('coolutility','core');
- //populate params array
- $params = Array();
- $params['object_type'] = $objectType;
- $params['object_id'] = $objectID;
- $params['cooler_id'] = $userID;
- $params['creation_date'] = new MongoDate();
- MyMongo_Connection::addDocument("cools", $params);
- $collection_name = $coolUtility->getItemCollection($objectType);
- // Add notification for owner of activity (if user and not viewer)
- if ($ownerID !== $userID) {
- Engine_Api::_ ()->getDbtable('notifications', 'activity')->addNotification($ownerID, $userID, $objectID, $objectType, 'liked', array(
- 'label' => $objectType
- ));
- }
- //MyMongo_Connection::updateAndOrIncCollectionFields($collection_name, array("_id" => $objectID), array(), array("cools_count" => 1));
- $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("cools_count" => 1)), array("cools_count" => 1));
- // Stats
- Engine_Api::_()->getDbtable('statistics', 'core')->increment('core.likes');
- return array(
- 'numOfCool' => $result['cools_count'] + 1
- );
- }
- /**
- * make an UnCOOL for a specified object
- * @param $objectID as a object
- * @param $objectType as a type of object
- * @param $userID user of author COOL
- * @return if response code is 200 returns json string format as {"numOfCool":"12"}
- */
- public function makeUnCool($objectID, $objectType, $userID) {
- $coolUtility = Engine_Api::_()->getApi('coolutility','core');
- $collection_name = $coolUtility->getItemCollection($objectType);
- $params = Array();
- $params['object_type'] = $objectType;
- $params['object_id'] = $objectID;
- $params['cooler_id'] = $userID;
- MyMongo_Connection::removeDocument("cools", $params);
- $result = MyMongo_Connection::findAndModify($collection_name, array("_id" => $objectID), array('$inc' => array("cools_count" => -1)), array("cools_count" => 1));
- return array(
- 'numOfCool' => $result['cools_count'] -1
- );
- }
- /**
- * send an email to the user's email adress whith link to reset account password.
- * @param $userID
- * @return if response code is 200 returns json string format as {"Response":"Request OK"}
- */
- public function forgotPassword($user) {
- try {
- MyMongo_Connection::removeDocument("user_forgot", array("user_id" => $user->_id));
- // Create a new reset password code
- $code = base_convert(md5($user->salt . $user->email . $user->_id . uniqid(time(), true)), 16, 36);
- MyMongo_Connection::addDocument("user_forgot", array("user_id" => $user->_id, "code" => $code, "creation_date" => new MongoDate()));
- $params =array(
- 'route' => 'user_profile',
- 'reset' => true,
- 'id' => $user->username,
- );
- $route = $params['route'];
- $reset = $params['reset'];
- unset($params['route']);
- unset($params['reset']);
- $recipient_link = Zend_Controller_Front::getInstance()->getRouter()->assemble($params, $route, $reset);
- $appName = Zend_Registry::get('Zend_View')->baseUrl(). "/";
- $gender = "B";
- if(isset($user->gender)) {
- $gender = $user->gender;
- }
- // Send user an email
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $objectLink = $appName . "user/auth/reset/code/" . $code . "/uid/" . $user->_id;
- Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'core_lostpassword', array(
- 'host' => $_SERVER['HTTP_HOST'],
- 'email' => $user->email,
- 'date' => time(),
- 'recipient_title' => $user->username,
- 'recipient_link' => $recipient_link,
- 'recipient_photo' => $appName."application/modules/User/externals/images/nophoto_user_thumb_profile_".$gender.".jpg",
- 'object_link' => $objectLink,
- 'queue' => false,
- ));
- return array(
- 'Response' => 'Request OK'
- );
- } catch( Exception $e ) {
- $errorArray = array('error', $e);
- return $errorArray;
- }
- }
- /**
- * it allows user to set new password.
- * @param $user
- * @param $newPsw the new password choosen for account authentication
- * @return if response code is 200 returns json string format as {"Response":"Request OK"}
- */
- public function setNewPassword($user, $newPsw){
- !isset($user->salt) ? $salt = (string)rand(1000000, 9999999) : $salt = $user->salt;
- $hashed_psw = md5(
- Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt') .
- $newPsw .
- $salt
- );
- try {
- MyMongo_Connection::removeDocument("user_forgot", array("user_id" => $user->_id));
- MyMongo_Connection::updateCollectionFields("users", array("_id" => $user->_id), array("password" => $hashed_psw, "salt" => $salt));
- return array(
- 'Response' => 'Request OK'
- );
- } catch( Exception $e ) {
- $errorArray = array('error', $e);
- return $errorArray;
- }
- }
- /**
- * Updates the user information
- *
- * @param
- * $userID
- * @param $updated_fields a
- * JSON string that contains all the updated fields
- * @return if response code is 200 returns json string format as {"Response":"Request OK"}
- */
- public function updateUserInfo($userID, $updated_fields) {
- $updatedArrays = Zend_Json_Decoder::decode($updated_fields, true); // decode JSON to associative array
- $userUtility = Engine_Api::_()->getApi('userutility', 'core');
- $userObject = $userUtility->getUser($userID);
- $accountType = $userObject->type;
- $update = $updatedArrays[0];
- if (array_key_exists("gender", $update) && (strcasecmp($accountType, "business") == 0)) {
- return array (
- "error",
- "gender parameter is not allowed for business account"
- );
- } elseif (array_key_exists("gender", $update)) {
- $genderchar = $update['gender'];
- if ($genderchar !== "M" && $genderchar !== "W") {
- return (array (
- "error" , "admitted values for gender parameter are M value for man, W value for woman"
- ));
- }
- }
- if (array_key_exists("birthday", $update) && (strcasecmp($accountType, "business") == 0)) {
- return array (
- "error",
- "birthday parameter is not allowed for business account"
- );
- } elseif (array_key_exists("birthday", $update)){
- $resultCheckDate = $this->checkFormatDate($update['birthday']);
- if (!$resultCheckDate[0]){
- return (array ("error" , $resultCheckDate[1]));
- }
- }
- if (array_key_exists("company_name", $update) && (strcasecmp($accountType, "personal") == 0)) {
- return array (
- "error",
- "company_name parameter is not allowed for personal account"
- );
- }
- if (array_key_exists("country", $update) && (strcasecmp($accountType, "personal") == 0)) {
- return array (
- "error",
- "country parameter is not allowed for personal account"
- );
- }
- if (array_key_exists("vat", $update) && (strcasecmp($accountType, "personal") == 0)) {
- return array (
- "error",
- "vat parameter is not allowed for personal account"
- );
- }
- if (array_key_exists("professional_work_fld", $update) && (strcasecmp($accountType, "personal") == 0)) {
- return array(
- "error",
- "professional_work_fld parameter is not allowed for personal account"
- );
- }
- if (array_key_exists("professional_work_fld", $update)) {
- $count = MyMongo_Connection::count("workfields", array("_id" => $update['professional_work_fld']));
- if($count <= 0) {
- return array(
- "error",
- "professional_work_fld value sent is not valid"
- );
- }
- }
- if (array_key_exists("profile_photo", $update) && (!(array_key_exists("profile_photo_rsz", $update)))) {
- return (array (
- "error" ,
- "both or neither parameters (profile_photo, profile_photo_rsz) must be provided"
- ));
- }
- if (!(array_key_exists("profile_photo", $update)) && array_key_exists ( "profile_photo_rsz", $update )) {
- return (array (
- "error" ,
- "both or neither parameters (profile_photo, profile_photo_rsz) must be provided"
- ));
- }
- if (array_key_exists("flow_photo", $update) && (!(array_key_exists ( "flow_photo_rsz", $update )))) {
- return (array (
- "error" ,
- "both or neither parameters (flow_photo, flow_photo_rsz) must be provided"
- ));
- }
- if (! (array_key_exists("flow_photo", $update)) && array_key_exists ( "flow_photo_rsz", $update )) {
- return (array (
- "error" ,
- "both or neither parameters (flow_photo, flow_photo_rsz) must be provided"
- ));
- }
- try {
- $updateArray = array();
- if (array_key_exists ( "name", $update )) {
- $updateArray['name'] = $update ['name'];
- }
- if (array_key_exists ( "surname", $update )) {
- $updateArray['surname'] = $update ['surname'];
- }
- if (array_key_exists ( "gender", $update )) {
- $updateArray['gender'] = ucfirst($update['gender']);
- }
- if (array_key_exists ( "birthday", $update )) {
- $updateArray['birthdate'] = new MongoDate(strtotime($update['birthday']));
- }
- if (array_key_exists("location", $update )) {
- $updateArray['location'] = $update['location'];
- }
- if (array_key_exists("company_name", $update)) {
- $updateArray['company'] = $update['company_name'];
- }
- if (array_key_exists ( "country", $update )) {
- $updateArray['country'] = $update['country'];
- }
- if (array_key_exists ( "vat", $update )) {
- $updateArray['vat'] = $update['vat'];
- }
- if (array_key_exists ( "personal_status", $update )) {
- $updateArray['status'] = htmlspecialchars($update['personal_status'],ENT_NOQUOTES);
- }
- if (array_key_exists ( "professional_work_fld", $update )) {
- $updateArray['workfield'] = $update['professional_work_fld'];
- }
- if (array_key_exists ( "interests", $update )) {
- $updateArray['interests'] = explode(',',$update ['interests']);
- }
- if (array_key_exists("profile_photo", $update) && array_key_exists("profile_photo_rsz", $update)) {
- // the configuration (ini) file where are written paths
- $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
- // get the array with property refers paths (it reads path.ini)
- $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
- $temporaryPath = $arrayPathProp ['temporaryPath'];
- // this is the photo name compliant to SocialEngine
- $photoCompliantName = md5 ( uniqid ( microtime () ) );
- // create the phisically image in the specified path
- $imagebase64 = $update ['profile_photo'];
- $imagebase64 = str_replace ( " ", "+", $imagebase64 );
- if (strlen($imagebase64) == 0) {
- $updateArray['fullsize_profilephoto_url'] = "";
- $updateArray['cropped_profilephoto_url'] = "";
- } else {
- list($x, $y, $w, $h) = explode(':', $update['profile_photo_rsz']);
- $createFile = $this->createImageProfileAndFlowFromBase64String ( $imagebase64, $temporaryPath, $photoCompliantName );
- $extension = $createFile['extension'];
- $filesize = $createFile['filesize'];
- $pathImage = $createFile['pathimage'];
- if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
- $imgExpl = explode("/", $pathImage);
- $img = $imgExpl[sizeof($imgExpl)-1];
- $img_name = explode(".", $img)[0];
- $final_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
- // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
- if($extension == "jpg" || $extension == "jpeg") {
- $im = imagecreatefromjpeg($pathImage);
- imageinterlace($im , true);
- imagejpeg($im , $pathImage, 100);
- imagedestroy($im);
- }
- if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $updateArray['fullsize_profilephoto_url'] = $final_img_name;
- // handle cropped photo
- $iProfilePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
- $final_croppped_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $imageOriginal = Engine_Image::factory();
- $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 120, 120)->write($iProfilePath)->destroy();
- // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
- if($extension == "jpg" || $extension == "jpeg") {
- $im = imagecreatefromjpeg($iProfilePath);
- imageinterlace($im , true);
- imagejpeg($im , $iProfilePath, 100);
- imagedestroy($im);
- }
- if ($s3->putObjectFile($iProfilePath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $val = unlink($iProfilePath);
- if(!$val) {
- Utilities_Static::log("ERROR on unlink file: ".$iProfilePath);
- }
- $updateArray['cropped_profilephoto_url'] = $final_croppped_img_name;
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $iProfilePath);
- @unlink($iProfilePath);
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- @unlink($pathImage);
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $iMainPath);
- @unlink($pathImage);
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- } else {
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- }
- }
- if (array_key_exists ( "flow_photo", $update ) && array_key_exists ( "flow_photo_rsz", $update )) {
- // the configuration (ini) file where are written paths
- $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
- // get the array with property refers paths (it reads path.ini)
- $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
- $temporaryPath = $arrayPathProp ['temporaryPathFlowPhoto'];
- // this is the photo name compliant to SocialEngine
- $photoCompliantName = md5 ( uniqid ( microtime () ) );
- // create the phisically image in the specified path
- $imagebase64 = $update ['flow_photo'];
- $imagebase64 = str_replace ( " ", "+", $imagebase64 );
- if (strlen ( $imagebase64 ) == 0) {
- $updateArray['fullsize_flowphoto_url'] = "";
- $updateArray['cropped_flowphoto_url'] = "";
- } else {
- list($x, $y, $w, $h) = explode(':', $update['flow_photo_rsz']);
- $createFile = $this->createImageProfileAndFlowFromBase64String ( $imagebase64, $temporaryPath, $photoCompliantName );
- $extension = $createFile ['extension'];
- $filesize = $createFile ['filesize'];
- $pathImage = $createFile ['pathimage'];
- if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
- $imgExpl = explode("/", $pathImage);
- $img = $imgExpl[sizeof($imgExpl)-1];
- $img_name = explode(".", $img)[0];
- // create a photo and file record
- $final_img_name = "public/user_ext/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
- if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $updateArray['fullsize_flowphoto_url'] = $final_img_name;
- // handle cropped photo
- $iFlowPath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
- $final_croppped_img_name = "public/user_ext/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $imageOriginal = Engine_Image::factory();
- $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 790, 140)->write($iFlowPath)->destroy();
- if ($s3->putObjectFile($iFlowPath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $val = unlink($iFlowPath);
- if(!$val) {
- Utilities_Static::log("ERROR on unlink file: ".$iFlowPath);
- }
- $updateArray['cropped_flowphoto_url'] = $final_croppped_img_name;
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $iFlowPath);
- @unlink($iFlowPath);
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- @unlink($pathImage);
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $pathImage);
- @unlink($pathImage);
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- } else {
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- }
- }
- // Update user document
- $unsetArray = array();
- if(isset($updateArray['fullsize_profilephoto_url']) && $updateArray['fullsize_profilephoto_url'] === "") {
- // unset profile photo
- $unsetArray['fullsize_profilephoto_url'] = 1;
- $unsetArray['cropped_profilephoto_url'] = 1;
- unset($updateArray['fullsize_profilephoto_url']);
- unset($updateArray['cropped_profilephoto_url']);
- }
- if(isset($updateArray['fullsize_flowphoto_url']) && $updateArray['fullsize_flowphoto_url'] === "") {
- //unset flow photo
- $unsetArray['fullsize_flowphoto_url'] = 1;
- $unsetArray['cropped_flowphoto_url'] = 1;
- unset($updateArray['fullsize_flowphoto_url']);
- unset($updateArray['cropped_flowphoto_url']);
- }
- if(sizeof($updateArray) > 0)
- {
- MyMongo_Connection::setAndUnsetFields("users", array("_id" => $userID), $updateArray, $unsetArray);
- }
- else
- {
- if(sizeof($unsetArray) > 0)
- {
- MyMongo_Connection::unsetFields("users", array("_id" => $userID), $unsetArray);
- }
- }
- } catch(Exception $e) {
- $errorArray = array (
- 'error',
- 'db error'
- );
- return $errorArray;
- }
- return array (
- 'Response' => 'Request OK'
- );
- }
- private function generateRandomValue() {
- $rand = dechex(rand(0,99));
- if(strlen($rand) == 1) {
- $rand = "0" . $rand;
- }
- return $rand;
- }
- /**
- * This method gets field_id associated to the label ($param) in record given ($metaInf)
- * @param $param label
- * @param $metaInf record
- * @return field_id
- */
- public function getFieldIdMetaInfoUser($param, $metaInf){
- foreach ($metaInf as $inf){
- if (strcasecmp($inf["label"], $param) == 0){
- return $inf["field_id"];
- }
- }
- }
- /**
- * This method return number associate to the gender given ($genderString could be m[male] or w[female])
- * @param $genderString
- * @return a number (2,3)
- */
- public function getGender($genderString){
- //$log = Zend_Registry::get ( 'Zend_Log' );
- $queryMale = "SELECT option_id FROM `engine4_user_fields_options` WHERE label='M' AND field_id=5";
- $queryFemale = "SELECT option_id FROM `engine4_user_fields_options` WHERE label='W' AND field_id=5";
- if (strcasecmp("m",$genderString) == 0){
- $adapter = Zend_Db_Table_Abstract::getDefaultAdapter ();
- $stmt = $adapter->query ( $queryMale );
- $code = $stmt->fetchAll ();
- return $code[0]['option_id'];
- }
- if (strcasecmp("w",$genderString) == 0){
- $adapter = Zend_Db_Table_Abstract::getDefaultAdapter ();
- $stmt = $adapter->query ( $queryFemale );
- $code = $stmt->fetchAll ();
- return $code[0]['option_id'];
- }
- return null;
- }
- /**
- * This method check if a data is valid and if birth date is a valid date
- * for socialmatic policy
- * @param $date
- * @return array(boolean,string) [string is a message]
- */
- public function checkFormatDate($date) {
- // value string must be in the form of yyyy-mm-dd
- if (preg_match ( "/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date )) {
- $minAge = 12;
- // Validate for users over X years only
- $date = strtotime ($date);
- // The age to be over, over +18
- $min = strtotime("+" . $minAge . " years", $date);
- if (time() < $min) {
- return array(false,"you are too young");
- }
- return array(true,"");
- } else {
- return array(false,"birthday field is incorrect. Birthday field value string must be in the form of yyyy-mm-dd");
- }
- }
- /**
- * Create a record in DB for table file storage to store info about profile photo.
- * @param $userID
- * @param $extension
- * @param $photoCompliantName
- * @param $filesize
- * @param $photoCompliantName
- * @return file_id for created file
- */
- public function createFileRecordProfilePhoto($userID, $extension, $photoCompliantName, $filesize, $coordinates, $pathImage, $temporaryPath) {
- $storage_service = Engine_Api::_()->getDbTable('services','storage')->getService(Engine_Api::_()->getDbTable('services','storage')->getDefaultServiceIdentity());
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
- $arrProp = $this->getPropertyArray ( $fullpathConfFile );
- $storagePath = $arrProp ['localPathImage'] . $photoCompliantName . "_m." . $extension;
- $storageThumbPath = $arrProp ['localPathImage'] . $photoCompliantName . "_s." . $extension;
- $paramsMain = array(
- 'parent_type' => "user",
- 'parent_id' => $userID,
- 'user_id' => $userID,
- 'name' => $photoCompliantName."_m.".$extension,
- );
- $iMain = $filesTable->createFile($storagePath, $paramsMain);
- $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
- list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
- $image = Engine_Image::factory();
- $image->open($pathImage);
- $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath)->destroy();
- $paramsThumb = array(
- 'parent_type' => "user",
- 'parent_id' => $userID,
- 'user_id' => $userID,
- 'name' => $photoCompliantName."_s.".$extension,
- );
- $iProfile = $filesTable->createFile($storageThumbPath, $paramsThumb);
- $iMain->bridge($iProfile, 'thumb.profile');
- if($storage_service->getType() == "s3") {
- // Remove temp files
- @unlink($storagePath);
- @unlink($storageThumbPath);
- }
- return $iMain->file_id;
- }
- /**
- * Create a record for table file storage to store info about flow photo.
- * @param $userID
- * @param $extension
- * @param $photoCompliantName
- * @param $filesize
- * @param $photoCompliantName
- * @return unknown
- */
- public function createFileRecordFlowPhoto($userID, $extension, $photoCompliantName, $filesize, $coordinates, $pathImage, $temporaryPath){
- $storage_service = Engine_Api::_()->getDbTable('services','storage')->getService(Engine_Api::_()->getDbTable('services','storage')->getDefaultServiceIdentity());
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
- $arrProp = $this->getPropertyArray($fullpathConfFile);
- $storagePath = $arrProp['localPathFlowPhoto'].$photoCompliantName."_m.".$extension;
- $storageThumbPath = $arrProp ['localPathFlowPhoto'] . $photoCompliantName . "_s." . $extension;
- $paramsMain = array(
- 'parent_type' => "user_ext",
- 'parent_id' => $userID,
- 'user_id' => $userID,
- 'name' => $photoCompliantName."_m.".$extension,
- );
- $iMain = $filesTable->createFile($storagePath, $paramsMain);
- $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
- list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
- $image = Engine_Image::factory();
- $image->open($pathImage);
- $image->resample($myx, $myy, $myw, $myh, 790, 140)->write($iProfilePath)->destroy();
- $paramsThumb = array(
- 'parent_type' => "user_ext",
- 'parent_id' => $userID,
- 'user_id' => $userID,
- 'name' => $photoCompliantName."_s.".$extension,
- );
- $iProfile = $filesTable->createFile($storageThumbPath, $paramsThumb);
- $iMain->bridge($iProfile, 'thumb.flow');
- if($storage_service->getType() == "s3") {
- // Remove temp files
- @unlink($storagePath);
- @unlink($storageThumbPath);
- }
- return $iMain->file_id;
- }
- /**
- * Create a record for table file storage to store info about cropped photo.
- * @param $coordinates
- * @param $pathImage
- * @param $temporaryPath
- * @param $photoCompliantName
- * @param $idFileParent
- * @param $extension
- * @param $userID
- */
- public function createFileRecordPhotoCrop($coordinates,$pathImage,$temporaryPath,$photoCompliantName,$idFileParent,$extension, $userID){
- $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
- $arrProp = $this->getPropertyArray($fullpathConfFile);
- $storagePath = $arrProp['localPathImage'].$photoCompliantName."_s.".$extension;
- $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
- list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
- $image = Engine_Image::factory();
- $image->open($pathImage);
- $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath);
- /*resized (thumb) PHOTO*/
- $params['type']= "thumb.profile";
- $params['parent_type'] = "user";
- $params['parent_file_id']= $idFileParent;
- $params['storage_path'] = $storagePath;
- $params['name'] = $photoCompliantName."_s.".$extension;
- $params['parent_id'] = $userID;
- $params['user_id'] = $userID;
- $params['service_id'] = "1";
- $params['extension'] = $extension;
- $params['mime_major'] = "image";
- $params['mime_minor'] = $extension;
- $params['size'] = filesize($pathImage);
- $params['hash'] = md5($photoCompliantName."_s.".$extension);
- //create a record (for thumb) in the albums table
- $file = Engine_Api::_()->getDbtable('files', 'storage')->createRow();
- //insert values
- $file->setFromArray($params);
- //commit
- $file->save();
- }
- /**
- * Create a record for table file storage to store info about cropped flow photo.
- * @param $coordinates
- * @param $pathImage
- * @param $temporaryPath
- * @param $photoCompliantName
- * @param $idFileParent
- * @param $extension
- * @param $userID
- */
- public function createFileRecordFlowCrop($coordinates,$pathImage,$temporaryPath,$photoCompliantName,$idFileParent,$extension, $userID){
- $fullpathConfFile = dirname( dirname(__FILE__) )."/settings/paths.ini";
- $arrProp = $this->getPropertyArray($fullpathConfFile);
- $storagePath = $arrProp['localPathFlowPhoto'].$photoCompliantName."_s.".$extension;
- $iProfilePath = $temporaryPath . $photoCompliantName . '_s.' . $extension;
- list($myx, $myy, $myw, $myh) = explode(':', $coordinates);
- $image = Engine_Image::factory();
- $image->open($pathImage);
- $image->resample($myx, $myy, $myw, $myh, 120, 120)->write($iProfilePath);
- /*resized (thumb) PHOTO*/
- $params['type']= "thumb.flow";
- $params['parent_type'] = "user_ext";
- $params['parent_file_id']= $idFileParent;
- $params['storage_path'] = $storagePath;
- $params['name'] = $photoCompliantName."_s.".$extension;
- $params['parent_id'] = $userID;
- $params['user_id'] = $userID;
- $params['service_id'] = "1";
- $params['extension'] = $extension;
- $params['mime_major'] = "image";
- $params['mime_minor'] = $extension;
- $params['size'] = filesize($pathImage);
- $params['hash'] = md5($photoCompliantName."_s.".$extension);
- //create a record (for thumb) in the albums table
- $file = Engine_Api::_()->getDbtable('files', 'storage')->createRow();
- //insert values
- $file->setFromArray($params);
- //commit
- $file->save();
- }
- /**
- * This method create a image from a base64 string and save it
- * in the specified path.
- * @param $byte the BASE64 string
- * @param $pathToSave path to save image
- * @param $imgName the image's name
- * @return file info created
- */
- public function createImageProfileAndFlowFromBase64String($byte, $pathToSave, $imgName)
- {
- //decode the base64
- $decodedImage=base64_decode($byte);
- //get the mime type array (0 is major (e.g. image) and 1 is minor (e.g. jpeg))
- $mime_arr = $this->getFileMIME($decodedImage);
- //create one photo
- $this->createPhoto($decodedImage, $pathToSave, $imgName, $mime_arr[1] );
- $fullpathFile=$pathToSave.$imgName;
- return array("extension" => $mime_arr[1], "filesize" => strlen($decodedImage), "pathimage" => $fullpathFile."_m.".$mime_arr[1]);
- }
- /**
- * This method create from a photo input a new photo resized.
- * @param $decodedData
- * @param $pathToSave
- * @param $imgName
- * @param $filetype
- */
- public function createPhoto($decodedData, $pathToSave, $imgName, $filetype )
- {
- $fullpathFile=$pathToSave.$imgName;
- @file_put_contents( $fullpathFile."_m.".$filetype, $decodedData );
- chmod($fullpathFile."_m.".$filetype, 0777);
- $name = basename($fullpathFile);
- $path = dirname($fullpathFile);
- $image = Engine_Image::factory();
- $image->open($fullpathFile."_m.".$filetype)->write($fullpathFile."_m.".$filetype)->destroy();
- }
- /**
- * this method allows user to register to Socialmatic Photo Network using mobile app
- * @param $deviceID
- * @param $deviceType
- * @param $registration_fields
- */
- public function userRegistration($deviceID,$deviceType,$registration_fields,$locale) {
- $registrationFields = Zend_Json_Decoder::decode($registration_fields, true); // decode JSON to associative array
- $userUtility = Engine_Api::_()->getApi('userutility', 'core');
- $textUtility = Engine_Api::_()->getApi('textutility', 'core');
- $user_table = Engine_Api::_()->getDbtable('users', 'user');
- $registration = $registrationFields [0];
- $errors = array();
- if (!(array_key_exists("email", $registration)))
- $errors["email"] = "email is mandatory parameter";
- if (!(array_key_exists("nickname", $registration)))
- $errors["nickname"] = "nickname is mandatory parameter";
- if (!(array_key_exists("password", $registration)))
- $errors["password"] = "password is mandatory parameter";
- if (! (array_key_exists("account_type", $registration)))
- $errors["account_type"] = "account_type is mandatory parameter";
- else if (!is_string($registration ['account_type'])) {
- $errors["account_type"] = "account_type value admitted is string";
- return array (
- "Response" => "Request KO",
- "errors" => $errors
- );
- } else if (!((strcasecmp($registration['account_type'], "0" ) == 0) || (strcasecmp($registration['account_type'], "1" ) == 0))) {
- $errors["account_type"] = "account_type value admitted are 0 or 1";
- return array (
- "Response" => "Request KO",
- "errors" => $errors
- );
- } else {
- $account_type = $registration ['account_type'];
- }
- if (! array_key_exists("name", $registration)) {
- $errors["name"] = "name is mandatory parameter";
- } elseif (strlen($registration["name"]) == 0) {
- $errors["name"] = "name cannot be empty";
- } elseif(!preg_match('/^[a-zA-Z]+[a-zA-Z ]+$/', $registration["name"])) {
- $errors["name"] = "name is not valid";
- }
- if (! array_key_exists("surname", $registration)) {
- $errors["surname"] = "surname is mandatory parameter";
- } elseif (strlen($registration["surname"]) == 0) {
- $errors["surname"] = "surname cannot be empty";
- } elseif(!preg_match('/^[a-zA-Z]+[a-zA-Z ]+$/', $registration["surname"])) {
- $errors["surname"] = "surname is not valid";
- }
- $genderchar = $registration['gender'];
- if (strcasecmp($account_type, "0") == 0 && (! array_key_exists("gender", $registration))) {
- $errors["gender"] = "gender parameter is mandatory for personal account";
- } elseif (strcasecmp($account_type, "1") == 0 && (array_key_exists("gender", $registration))) {
- $errors["gender"] = "gender parameter is not allowed for business account";
- }elseif (strcasecmp($account_type, "0") == 0 && array_key_exists("gender", $registration) && $genderchar != "M" && $genderchar != "W") {
- $errors["gender"] = "admitted values for gender parameter are M value for man, W value for woman";
- }
- $resultCheckDate = $this->checkFormatDate ( $registration ['birthday'] );
- if (array_key_exists ( "birthday", $registration ) && (strcasecmp ( $account_type, "1" ) == 0)) {
- $errors["birthday"] = "parameter birthday is not allowed for business account" ;
- } elseif (!(array_key_exists ( "birthday", $registration )) && ( strcasecmp ( $account_type, "0" ) == 0)) {
- $errors["birthday"] = "birthday parameter is mandatory for personal account";
- } elseif ((array_key_exists ( "birthday", $registration )) && ( strcasecmp ( $account_type, "0" ) == 0) && !($resultCheckDate [0])) {
- $errors["birthday"] = $resultCheckDate [1] ;
- }
- if (! array_key_exists("location", $registration)) {
- $errors["location"] = "location is mandatory parameter";
- } elseif (strlen($registration["location"]) == 0) {
- $errors["location"] = "location cannot be empty";
- } elseif($textUtility->isThereEmoji($registration["location"])) {
- $errors["location"] = "location is not valid";
- }
- if (array_key_exists("company_name", $registration) && strcasecmp($account_type, "0") == 0) {
- $errors["company_name"] = "company_name parameter is not allowed for personal account";
- }
- if (!(array_key_exists("company_name", $registration)) && strcasecmp($account_type, "1") == 0) {
- $errors["company_name"] = "company_name parameter is mandatory for business account";
- } elseif ((strlen($registration["company_name"]) == 0) && strcasecmp($account_type, "1") == 0) {
- $errors["company_name"] = "company_name cannot be empty";
- } elseif($textUtility->isThereEmoji($registration["company_name"]) && strcasecmp($account_type, "1") == 0) {
- $errors["company_name"] = "company_name is not valid";
- }
- if (array_key_exists("country", $registration) && strcasecmp($account_type, "0") == 0) {
- $errors["country"] = "country parameter is not allowed for personal account";
- }
- if (! (array_key_exists("country", $registration)) && strcasecmp($account_type, "1") == 0) {
- $errors["country"] = "country parameter is mandatory for business account";
- } elseif ((strlen($registration["country"]) == 0) && strcasecmp($account_type, "1") == 0) {
- $errors["country"] = "country cannot be empty";
- }
- if (array_key_exists("vat", $registration) && strcasecmp($account_type, "0") == 0) {
- $errors["vat"] = "vat parameter is not allowed for personal account";
- }
- if (! (array_key_exists("vat", $registration)) && strcasecmp($account_type, "1") == 0) {
- $errors["vat"] = "vat parameter is mandatory for business account";
- } elseif ((strlen($registration["vat"]) == 0) && strcasecmp($account_type, "1") == 0) {
- $errors["vat"] = "vat cannot be empty";
- } elseif($textUtility->isThereEmoji($registration["vat"]) && strcasecmp($account_type, "1") == 0) {
- $errors["vat"] = "vat is not valid";
- }
- if (array_key_exists("professional_work_fld", $registration) && strcasecmp($account_type, "0") == 0) {
- $errors["professional_work_fld"] = "professional_work_fld parameter is not allowed for personal account";
- }
- if (! (array_key_exists("professional_work_fld", $registration)) && strcasecmp($account_type, "1") == 0) {
- $errors["professional_work_fld"] = "professional_work_fld parameter is mandatory for business account";
- } elseif ((strlen($registration["professional_work_fld"]) == 0) && strcasecmp($account_type, "1") == 0) {
- $errors["professional_work_fld"] = "professional_work_fld parameter cannot be empty";
- } elseif((strlen($registration["professional_work_fld"]) > 0) && strcasecmp($account_type, "1") == 0) {
- $count = MyMongo_Connection::count("workfields", array("_id" => $registration["professional_work_fld"]));
- if($count != 1) {
- $errors["professional_work_fld"] = "professional_work_fld value not allowed";
- }
- }
- if (array_key_exists("profile_photo", $registration) && (!(array_key_exists("profile_photo_rsz", $registration)))) {
- $errors["profile_photo profile_photo_rsz"] ="both or neither parameters (profile_photo, profile_photo_rsz) must be provided";
- }
- if (! (array_key_exists("profile_photo", $registration)) && array_key_exists ( "profile_photo_rsz", $registration )) {
- $errors["profile_photo profile_photo_rsz"] ="both or neither parameters (profile_photo, profile_photo_rsz) must be provided";
- }
- if (array_key_exists("email",$registration)) {
- $validator = new Zend_Validate_EmailAddress();
- if (!$validator->isValid($registration["email"])) {
- $errors["email"] = 'You have entered a not valid mail!';
- } else {
- $result = MyMongo_Connection::count("users", array("email" => $registration["email"])); //$user_table->fetchAll($user_table->select()->where('email = ?',$registration["email"]));
- if($result > 0) {
- $errors["email"] = "email already used";
- }
- }
- }
- if (array_key_exists("password",$registration)){
- if (strlen($registration["password"]) < 6 || strlen($registration["password"]) > 32)
- $errors["password"] = "password must be at least 6 and less than 32 characters long";
- }
- if (array_key_exists("nickname", $registration)) {
- if(strlen(trim($registration['nickname'])) < 4 || strlen(trim($registration['nickname'])) > 32) {
- $errors["nickname"] = "nickname must be at least 6 and less than 32 characters long";
- } else {
- $userExtra = Engine_Api::_()->getApi('userextra', 'user');
- $nicknameDenied = $userExtra->getNicknameDeniedFromSettings();
- if (in_array(strtolower($registration["nickname"]), $nicknameDenied)){
- $errors["nickname"] = "nickname not allowed";
- } elseif (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/i', $registration['nickname'])) {
- $errors["nickname"] = "nickname must be contains only letters and numbers";
- } else {
- $result = MyMongo_Connection::count("users", array("username" => $registration["nickname"])); //$user_table->fetchAll($user_table->select()->where('username = ?',$registration["nickname"]));
- if ($result > 0) {
- $errors["nickname"] = "nickname already used";
- }
- }
- }
- }
- if (sizeof($errors) > 0){
- return array(
- "Response" => "Request KO",
- "errors" => $errors
- );
- }
- try {
- // IP
- $ipObj = new Engine_IP();
- // user key
- $charid = strtoupper(md5(uniqid(rand(), true)));
- $user_key = substr($charid, 0, 8) . '-' .
- substr($charid, 8, 8) . '-' .
- substr($charid, 16, 8) . '-' .
- substr($charid, 24, 8);
- $creation_date = new MongoDate();
- $_id = hash("md5", $registration["surname"] . $creation_date->__toString());
- $type = "personal";
- if(strcasecmp($registration ['account_type'], "1") == 0) {
- $type = "business";
- }
- // password
- $static_salt = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt');
- $salt = (string)rand(1000000, 9999999);
- $hashed_psw = md5($static_salt . $registration['password'] . $salt);
- $parametersArray = array();
- $parametersArray["_id"] = $_id;
- $parametersArray["email"] = $registration["email"];
- $parametersArray["username"] = $registration["nickname"];
- $parametersArray["name"] = $registration["name"];
- $parametersArray["surname"] = $registration["surname"];
- $parametersArray["type"] = $type;
- $parametersArray["status"] = "Welcome!";
- $parametersArray["password"] = $hashed_psw;
- $parametersArray["salt"] = $salt;
- $parametersArray["locale"] = $locale;
- $parametersArray["language"] = $locale;
- $parametersArray["timezone"] = Zend_Registry::get('timezone');
- $parametersArray["level"] = intval(4);
- $parametersArray["invites_used"] = intval(0);
- $parametersArray["extra_invites"] = intval(0);
- $parametersArray["enabled"] = false;
- $parametersArray["disabled_by_admin"] = false;
- $parametersArray["authentic"] = false;
- $parametersArray["creation_date"] = $creation_date;
- $parametersArray["creation_ip"] = $ipObj->toLong();
- $parametersArray["modified_date"] = $creation_date;
- $parametersArray["followers_count"] = intval(0);
- $parametersArray["following_count"] = intval(0);
- $parametersArray["views_count"] = intval(0);
- $parametersArray["updates_subscribed"] = true;
- if (array_key_exists("profile_photo", $registration ) && array_key_exists("profile_photo_rsz", $registration)) {
- // the configuration (ini) file where are written paths
- $fullpathConfFile = dirname ( dirname ( __FILE__ ) ) . "/settings/paths.ini";
- // get the array with property refers paths (it reads path.ini)
- $arrayPathProp = $this->getPropertyArray ( $fullpathConfFile );
- $temporaryPath = $arrayPathProp ['temporaryPath'];
- // this is the photo name compliant to SocialEngine
- $photoCompliantName = md5 ( uniqid ( microtime () ) );
- // create the phisically image in the specified path
- $imagebase64 = $registration ['profile_photo'];
- $imagebase64 = str_replace(" ", "+", $imagebase64);
- $createFile = $this->createImageProfileAndFlowFromBase64String($imagebase64, $temporaryPath, $photoCompliantName);
- $extension = $createFile ['extension'];
- $filesize = $createFile ['filesize'];
- $pathImage = $createFile ['pathimage'];
- if(isset($createFile['pathimage']) && $createFile['pathimage'] != null && $createFile['pathimage'] != "") {
- list($x, $y, $w, $h) = explode(':', $registration['profile_photo_rsz']);
- $imgExpl = explode("/", $pathImage);
- $img = $imgExpl[sizeof($imgExpl)-1];
- $img_name = explode(".", $img)[0];
- $final_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $s3 = new s3upload_S3(awsAccessKey, awsSecretKey);
- // Convert main photo to Progressive JPEG if img type is .jpg or .jpeg
- if($extension == "jpg" || $extension == "jpeg") {
- $im = imagecreatefromjpeg($pathImage);
- imageinterlace($im , true);
- imagejpeg($im , $pathImage, 100);
- imagedestroy($im);
- }
- if ($s3->putObjectFile($pathImage, bucket, $final_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $parametersArray["fullsize_profilephoto_url"] = $final_img_name;
- // handle cropped photo
- $iProfilePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . uniqid($img_name) . '_is.' . $extension;
- $final_croppped_img_name = "public/user/" . $this->generateRandomValue() . "/" . md5(uniqid($img_name)) . "." . $extension;
- $imageOriginal = Engine_Image::factory();
- $imageOriginal->open($pathImage)->resample($x, $y, $w, $h, 120, 120)->write($iProfilePath)->destroy();
- // Convert thumb photo to Progressive JPEG if img type is .jpg or .jpeg
- if($extension == "jpg" || $extension == "jpeg") {
- $im = imagecreatefromjpeg($iProfilePath);
- imageinterlace($im , true);
- imagejpeg($im , $iProfilePath, 100);
- imagedestroy($im);
- }
- if ($s3->putObjectFile($iProfilePath, bucket, $final_croppped_img_name, s3upload_S3::ACL_PUBLIC_READ)) {
- $val = unlink($iProfilePath);
- if(!$val) {
- Utilities_Static::log("ERROR on unlink file: ".$iProfilePath);
- }
- $parametersArray["cropped_profilephoto_url"] = $final_croppped_img_name;
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $iProfilePath);
- @unlink($iProfilePath);
- unset($parametersArray['fullsize_profilephoto_url']);
- }
- @unlink($pathImage);
- } else {
- Utilities_Static::log("ERROR while uploading file: " . $iMainPath);
- @unlink($pathImage);
- }
- }
- }
- $parametersArray["current_rank"] = intval(0);
- $parametersArray["previous_rank"] = intval(0);
- $parametersArray["update_rank_date"] = $creation_date;
- $parametersArray["enable_msg_enter_btn"] = false;
- $parametersArray["user_key"] = $user_key;
- $parametersArray["is_public"] = true;
- if (array_key_exists("gender", $registration)){
- $parametersArray["gender"] = $registration["gender"];
- }
- if (array_key_exists("birthday",$registration)){
- $parametersArray["birthdate"] = new MongoDate(strtotime($registration["birthday"]));
- }
- if (array_key_exists("location", $registration)) {
- $parametersArray["location"] = $registration["location"];
- }
- if (array_key_exists("company_name",$registration)) {
- $parametersArray["company"] = $registration["company_name"];
- }
- if (array_key_exists("country",$registration)) {//es. US for United States
- $parametersArray["country"] = $registration["country"];
- }
- if (array_key_exists("vat",$registration)) {
- $parametersArray["vat"] = $registration["vat"];
- }
- if (array_key_exists("professional_work_fld",$registration)) {
- $parametersArray["workfield"] = $registration["professional_work_fld"];
- }
- $settings = array();
- $settings['photo_seen'] = false;
- $settings['photo_moved'] = false;
- $settings['message_new'] = false;
- $settings['friend_follow'] = false;
- $settings['commented_mention'] = false;
- $parametersArray["notification_settings"] = $settings;
- MyMongo_Connection::addDocument("users", $parametersArray);
- // send verification mail
- $verify_array = array (
- 'code' => md5($parametersArray["email"] . $parametersArray["creation_date"]->__toString() . Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt') . (string) rand(1000000, 9999999)),
- 'date' => $parametersArray["creation_date"]
- );
- MyMongo_Connection::updateCollectionFields("user_verify", array("user_id" => $parametersArray["_id"]), $verify_array, array('upsert' => true));
- $mailParams = array (
- 'host' => $_SERVER['HTTP_HOST'],
- 'email' => $parametersArray["email"],
- 'date' => time(),
- 'recipient_title' => $parametersArray["username"],
- 'recipient_link' => Utilities_Static::getUserutility()->getUserHref((object)$parametersArray),
- 'recipient_photo' => Utilities_Static::getUserutility()->getUserPhotoURL((object)$parametersArray, true),
- 'queue' => false
- );
- $mailParams['object_link'] = Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'verify'), 'user_signup', true) . '?' . http_build_query(array(
- 'email' => $parametersArray["email"],
- 'verify' => $verify_array["code"]
- ));
- Engine_Api::_()->getApi('mail', 'core')->sendSystem((object)$parametersArray, 'core_verification', $mailParams);
- } catch ( Exception $e ) {
- return array(
- "Response" => "Request KO",
- "errors" => array("DB Error" => "Error while saving data")
- );
- }
- return array (
- 'Response' => 'Request OK'
- );
- }
- /**
- * Consente a $userID di seguire $userIDToFollow
- * @param $userID
- * @param $userIDToFollow
- * @return multitype:string
- */
- public function addFriend($userID, $userIDToFollow)
- {
- //verifico se l'utente sta tentando di seguire se stesso
- if (strcmp ( $userID, $userIDToFollow ) == 0)
- {
- return array (
- 'error',
- 'You cannot befriend yourself'
- );
- }
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- //verifico se $userID non segue l'owner della foto
- if( !$userUtility->isFollowing($userID, $userIDToFollow) )
- {
- //esegue la logica di following (inviando la notifica di nuovo follower all'owner della foto)
- Engine_Api::_()->user()->followSMUser
- (
- MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userID)),
- MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userIDToFollow))
- );
- return array ('Response' => 'Request OK');
- }
- else
- {
- return array('error', 'Relation already exists');
- }
- }
- /**
- * it returns the flow of actions for the user that makes the request.
- * @param $userID
- * @param $lastReceivedID
- * @param $numOfActions
- * @param $isMinId: if value of this boolean var is false, then $lastReceivedID corresponds to a max_id
- */
- public function getFlow ($userID,$lastReceivedID,$numOfActions, $isMinId=true)
- {
- $activityUtility = Engine_Api::_()->getApi("activityutility","activity");
- return $activityUtility->getFeed ($userID,$lastReceivedID,$numOfActions, $isMinId, true);
- }
- /**
- *
- * @param $userID
- * @param $photoIDorObject
- * @return returns a string in JSON format
- */
- public function getPhoto ($userID, $photoIDorObject) {
- if(is_string($photoIDorObject)) {
- $photo = MyMongo_Connection::findOne("photos", array("_id" => $photoIDorObject));
- } else {
- $photo = (object) $photoIDorObject;
- }
- $coolUtility = Engine_Api::_()->getApi("coolutility","core");
- $photoUtility = Engine_Api::_()->getApi('photoutility', 'core');
- $userUtility = Engine_Api::_()->getApi('userutility', 'core');
- $photoseeArray = $photoUtility->getPhotoSeeFlattened($photo->_id);
- $photoTags = (array)$photoUtility->getPhotoTags($photo);
- $arrayCities = $photoUtility->getAllCoordinates($photo);
- $uploadCity = $arrayCities[0]["city"];
- $uploadLat = $arrayCities[0]["lat"];
- $uploadLon = $arrayCities[0]["lon"];
- $arrayCities = $photoUtility->getPhotoCities($photo);
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $photoURLThumb = SM_BUCKET . $photo->thumb_img["url"];
- $photoURL = SM_BUCKET . $photo->fullsize_img["url"];
- $qrDetails = 'https://'.$_SERVER['HTTP_HOST'].$appName."user/photodetail/view?p=".$photo->_id;
- $already_followed = $userUtility->isFollowing($userID, $photo->owner_id);
- $ownerArray = $this->getUserDetails($photo->owner_id);
- $ownerArray["already_followed"] = $already_followed;
- $pins_counter = $photo->moves_count;
- if(isset($photo->upload_position)) {
- $pins_counter++;
- }
- $user_cool = $coolUtility->isCooler($userID, 'photo', $photo->_id);
- $result = array(
- 'photo_id' => $photo->_id,
- 'photo_description' => $photo->title,
- 'photo_see' => $photoseeArray,
- 'photo_tags' => $photoTags,
- 'photo_miles' => $photo->distance,
- 'upload_city' => urlencode($uploadCity),
- 'upload_lat' => $uploadLat,
- 'upload_lon' => $uploadLon,
- 'map_upload_img_url' => SM_BUCKET . $photo->map_upload_img_url,
- 'upload_date' => $photo->creation_date->sec,
- 'photo_url_thumb' => $photoURLThumb,
- 'photo_url' => $photoURL,
- 'user_cool' => intval($user_cool),
- "pin_counter" => $pins_counter,
- "comment_counter" => $photo->comments_count,
- "cool_counter" => $photo->cools_count,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $photo->img_orientation,
- 'photo_cities' => $arrayCities,
- 'photo_upload_date' => $photo->creation_date->sec
- );
- return array(
- 'photo' => $result,
- 'owner' => $ownerArray
- );
- }
- /**
- * Returns the comments list for a specified object.
- * @param $objectID
- * @param $objectType
- * @return returns a string in JSON format
- */
- public function commentList($objectID, $objectType) {
- $commentsArray = MyMongo_Connection::find("comments", array("object_id" => $objectID, "object_type" => $objectType), array(), array("creation_date" => 1));
- if (sizeof(iterator_to_array($commentsArray)) == 0) {
- $errorArray = array();
- return $errorArray;
- } else {
- $result = array();
- $i = 0;
- foreach ($commentsArray as $comment){
- $userDetails = $this->getUserDetails($comment["poster_id"]);
- $result[$i] = array(
- 'comment_id' => $comment["_id"],
- 'comment_body' => $comment["body"],
- 'comment_date' => $comment["creation_date"]->sec,
- 'poster' => $userDetails
- );
- $i++;
- }
- return $result;
- }
- }
- /**
- *
- * @param $userID
- * @param $recipientList
- * @param $comment
- * @return
- */
- public function sendNewMessage($userID, $recipientList, $comment, $conversationID=null)
- {
- $comment = htmlspecialchars($comment,ENT_NOQUOTES);
- $recipients = explode ( ",", $recipientList );
- //conterrà la lista degli altri utenti a cui sarà inviata la push (se hanno un device)
- $usersToPush = $recipients;
- if (sizeof ( $recipients ) == 0)
- {
- $errorArray = array
- (
- 'error' => 'recipient list is empty'
- );
- return $errorArray;
- }
- $participants = array(); //sarà inserito nell'array da salvare nel db
- $visibleTo = "|".$userID."|"; //stringa che indica che il messaggio deve essere visibile a tutti i partecipanti compreso chi lo scrive
- foreach ( $recipients as $recipient_id )
- {
- if (strcasecmp($userID,$recipient_id) == 0)
- {
- $errorArray = array (
- 'error' => "You can't send a message to yourself "
- );
- return $errorArray;
- }
- array_push($participants, array('user_id' => $recipient_id));
- $visibleTo.="|".$recipient_id."|";
- }
- array_push($participants, array('user_id' => $userID));//anche il creatore del messaggio è un participant per gli altri utenti che ricevono il messaggio
- array_push($recipients, $userID);//per creare il conversationID è necessario anche l'id del creatore del messaggio
- $participantsArray = $recipients;
- if(is_null($conversationID))
- {
- //OTTENGO IL CONVERSATION ID UNIVOCO PER I PARTECIPANTI CORRENTI: INIZIO
- natsort($recipients);
- $conversationID = hash("md5",implode("",$recipients));
- //OTTENGO IL CONVERSATION ID UNIVOCO PER I PARTECIPANTI CORRENTI: FINE
- }
- $conversation_members_count = sizeof($recipients);
- $lastMessageDate = new MongoDate();
- $lastMessageBody = $comment;
- $messageMongoID = new MongoId();
- $participantsCursor = MyMongo_Connection::find(static::$usersCollection,array('_id' => array('$in' => $participantsArray)),
- array('username' => 1, '_id' => 1));
- $participantsParamsForPushNotificationArr = array();
- foreach ($participantsCursor as $currUserPart)
- {
- array_push($participantsParamsForPushNotificationArr, array('user_id' => $currUserPart['_id'], 'nickname' => $currUserPart['username']));
- }
- // Create recipients inbox
- foreach ( $recipients as $recipient_id )
- {
- $currParticipants = $this->removeOwnerFromParticipants($recipient_id, $participants);
- $read = strcasecmp($recipient_id, $userID) == 0 ? true : false; //il creatore del messaggio ha letto la conversazione in cui scrive
- //creo o aggiorno la casella per la conversazione per l'utente corrente (compreso il creatore del messaggio)
- MyMongo_Connection::updateCollectionFields(static::$conversationsColl,
- array('conversation_id' => $conversationID, 'owner_id' => $recipient_id),
- array ( 'participants' => $currParticipants, 'read' => $read, 'deleted' => false, 'last_sender_id' => $userID,
- 'last_message_body' => $comment, 'last_message_date' => $lastMessageDate, 'conversation_members_count' => $conversation_members_count
- ),
- array('upsert' => true)
- );
- if(strcasecmp($userID, $recipient_id) != 0)
- {
- //aggiunge le notifiche per gli utenti che non sono il sender
- Engine_Api::_()->getDbtable('notifications', 'activity')->addNotificationExceptPushNotification
- (
- $recipient_id,
- $userID,
- $conversationID,
- 'conversation',
- 'message_new',
- array('message_id'=>$messageMongoID->__toString(),'message_body' => $comment, 'creation_date' => $lastMessageDate->sec,
- 'participants' => $participantsParamsForPushNotificationArr
- )
- );
- }
- }
- $messageToAdd = array('_id' => $messageMongoID, 'conversation_id' => $conversationID, 'sender_id' => $userID,
- 'body' => $comment, 'creation_date' => $lastMessageDate, 'visible_to' => $visibleTo
- );
- // Create message
- MyMongo_Connection::addDocument(static::$messagesColl, $messageToAdd);
- $response = array (
- "conversation_id" => $conversationID,
- "msg_id" => $messageMongoID->__toString()
- );
- //invio le push notifications agli utenti
- Engine_Api::_()->getApi("activityutility","activity")->sendInstantNotificationToAllPlatformsForMultipleUsers($usersToPush,false,$userID);
- return $response;
- }
- /**
- * Restituisce l'array dei partecipanti senza l'utente specificato
- * @param $participants
- * @return array di partecipanti senza l'utente specificato
- */
- private function removeOwnerFromParticipants($userIDToRemove, $participants)
- {
- $toReturn = $participants;
- $dim = sizeof($toReturn);
- for($i = 0; $i < $dim; $i++)
- {
- if(strcasecmp($userIDToRemove, $toReturn[$i]['user_id']) == 0)
- {
- unset($toReturn[$i]);
- break;
- }
- }
- //array_values azzera gli indici dell'array
- return array_values($toReturn);
- }
- /**
- * This method returns all of my events and those posted by my friends
- * @param $userID
- */
- public function getEvents($userID) {
- $eventAuxiliary = Engine_Api::_()->getApi('eventauxiliary', 'event');
- $userUtility = Engine_Api::_()->getApi('userutility', 'core');
- $events = $eventAuxiliary->getEventsByUserID($userID, null, null, true, false);
- $arrayEvents = array();
- $i = 0;
- foreach ($events as $event) {
- $photoURLCompleted = SM_BUCKET . $event["img_url"];
- $user = $this->getUserDetails($event["owner_id"]);
- $elementEvents = array (
- 'event_id' => $event["_id"],
- 'title' => $event ["title"],
- 'description' => $event ["description"],
- 'starttime' => $event["start_time"]->sec,
- 'photo_url' => $photoURLCompleted,
- 'member_count' => $event ["attenders_count"],
- 'image_orientation' => $event["img_orientation"],
- 'view_count' => $event ["views_count"],
- 'qr_details' => "https://".$_SERVER['HTTP_HOST'].$eventAuxiliary->getEventHref(((object) $event)),
- 'location_img_url' => SM_BUCKET . $event["location_img_url"]
- );
- $arrayEvents[$i] = array (
- "event" => $elementEvents,
- "owner" => $user
- );
- $i++;
- }
- $userUtility->resetNotificationTypeForUser($userID, "event_create");
- return $arrayEvents;
- }
- /**
- * this method return all information of specified event
- *
- * @param $userID
- * @param $event_id
- */
- public function getEventInfo($userID, $event_id)
- {
- $event = MyMongo_Connection::findOne(static::$eventsColl, array('_id' => $event_id));
- if (is_null($event))
- {
- $errorArray = array (
- 'error' => 'specified event does not exist'
- );
- return $errorArray;
- }
- $startTime = $event->start_time->toDateTime()->getTimestamp();
- $endTime = $event->end_time->toDateTime()->getTimestamp();
- $userOwner = MyMongo_Connection::findOne(static::$usersCollection, array('_id' => $event->owner_id));
- $currentUserMembershipRsvp = MyMongo_Connection::findOne(static::$eventMemberColl, array('user_id' => $userID, 'event_id' => $event_id));
- $currRSVP = "";
- //se non è presente l'utente nella membership dell'utente corrente
- if(is_null($currentUserMembershipRsvp))
- {
- $currRSVP = 3;
- MyMongo_Connection::addDocument(static::$eventMemberColl, array('event_id'=>$event_id, 'user_id' => $userID, 'rsvp' => $currRSVP));
- }
- else
- {
- $currRSVP = $currentUserMembershipRsvp->rsvp;
- }
- $photoURLCompleted = SM_BUCKET.$event->img_url;
- // Incremento il contatore di visualizzazioni se non è l'owner dell'evento
- if( strcasecmp($event->owner_id , $userID) != 0 )
- {
- MyMongo_Connection::updateAndOrIncCollectionFields(static::$eventsColl, array('_id' => $event_id), array(), array('views_count' => 1));
- }
- return array
- (
- 'event_id' => $event->_id,
- 'title' => $event->title,
- 'description' => $event->description,
- 'starttime' => $startTime,
- 'endtime' => $endTime,
- 'photo_url' => $photoURLCompleted,
- 'category' => $event->category,
- 'location' => $event->location['address'],
- 'latitude' => $event->location['lat'],
- 'longitude' => $event->location['lon'],
- 'exist_friendship_channel' => Utilities_Static::getUserutility()->checkFriendshipChannelBetweenTwoUsers($event->owner_id,$userID),
- 'participants_number' => $event->attenders_count,
- 'event_cools' => $event->cools_count,
- 'owner' => $this->getUserDetails ( $event->owner_id ),
- 'user_cool' => Engine_Api::_ ()->getApi ( "coolutility", "core" )->isCooler($userID,'event',$event_id) ? 1 : 0,
- 'image_orientation' => $event->img_orientation,
- 'is_public' => $userOwner->is_public,
- 'userlogged_rsvp' => $currRSVP,
- 'comment_counter' => $event->comments_count,
- 'location_img_url' => SM_BUCKET.$event->location_img_url,
- 'views' => $event->views_count
- );
- }
- // function to get the address
- public function get_lat_long($address){
- $address = str_replace(" ", "+", $address);
- $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
- $json = json_decode($json);
- $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
- $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
- return array("lat" => $lat, "lon" => $long);
- }
- /**
- * this method set response of user to event invite
- * @param $userID
- * @param $eventID
- * @param $option
- */
- public function eventResponse($userID, $eventID, $option)
- {
- //verifica se $option è numerico ed appartentente all'intervallo [0,3[
- if (is_numeric($option) && ((int)$option >= 0) && ((int)$option < 3) )
- {
- $option = (int)$option;
- $event = MyMongo_Connection::findOne(static::$eventsColl, array('_id' => $eventID));
- //se l'evento non esiste
- if (is_null($event))
- {
- return array ('error' => 'specified event does not exist');
- }
- //aggiorna o inserisci l'intenzione di partecipazione per l'utente specificato nell'evento specificato
- MyMongo_Connection::updateCollectionFields
- (
- static::$eventMemberColl, array('event_id' => $eventID, 'user_id' => $userID),
- array('rsvp' => $option),
- array('upsert' => true)
- );
- $acceptorsCount = MyMongo_Connection::count(static::$eventMemberColl, array('event_id' => $eventID, 'rsvp' => 2));
- MyMongo_Connection::updateCollectionFields(static::$eventsColl,array('_id' => $eventID), array('attenders_count' => (int)$acceptorsCount ));
- return array('Response' => 'Request OK');
- }
- else
- {
- return array ('error' => 'option value must be set to 0 or 1 or 2');;
- }
- }
- public function getOpenOffers($userID) {
- $userRequester = Engine_Api::_()->user()->getUser($userID);
- $offers = MyMongo_Connection::find("offers", array("closed" => false), array(), array("creation_date" => -1));
- $arrayOffers = array();
- $i = 0;
- foreach($offers as $offer) {
- $user = MyMongo_Connection::findOne("users", array("_id" => $offer['owner_id']));
- $limitedValue = "No";
- $limitData = isset($offer['limitations']['params']['expiration_date']) ? $offer['limitations']['params']['expiration_date']->sec : null;
- $limitTypeValue = isset($offer['limitations']['params']['type']) ? $offer['limitations']['params']['type'] : null;
- if($limitTypeValue != null) {
- $limitedValue = "Yes";
- }
- $startTime = $offer["creation_date"]->sec;
- $dateStart = new Zend_Date($startTime );
- $dateStart->setTimezone($userRequester->timezone);
- $photoURLCompleted = SM_BUCKET . $offer['img_url'];
- $price = (int)$offer['price'];
- $currency = $offer['currency'];
- $location = $offer['location']['address'];
- $qrDetails = Engine_Api::_()->getApi("offerauxiliary","classified")->getOfferHref($offer, true);
- if (isset($limitTypeValue)) {
- if (isset($limitData)) {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'limit_type' => $limitTypeValue,
- 'limit_date' => $limitData,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- } else {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'limit_type' => $limitTypeValue,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- }
- } else {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- }
- $userDetails = $this->buildUserArr((array)$user);
- $arrayOffers [$i] = array(
- 'offer' => $elementOffers,
- 'owner' => $userDetails
- );
- $i++;
- }
- Engine_Api::_()->getApi('userutility', 'core')->resetNotificationTypeForUser($userID, "classified_new");
- return $arrayOffers;
- }
- /**
- * Ritorna il dettaglio di una offerta
- * @param $userID
- * @param $offerID
- * @return
- */
- public function getOfferInfo ( $userID, $offerID, $fromWS=false )
- {
- $coolUtility = Engine_Api::_()->getApi("coolutility","core");
- $offerAux = Engine_Api::_()->getApi("offerauxiliary","classified");
- $offer = (array)MyMongo_Connection::findOne(static::$offersColl, array('_id' => $offerID));
- if(isset($offer["_id"])) {
- $expired = false;
- if(!is_null($offer['limitations']['params']['expiration_date']))
- {
- $today = new MongoDate();
- $today = $today->sec;
- $expired = $offer['limitations']['params']['expiration_date']->sec < $today;
- }
- //incremento di 1 il contatore visite
- MyMongo_Connection::updateAndOrIncCollectionFields(static::$offersColl, array('_id' => $offerID), array(), array('views_count' => 1));
- $canAccept = false;
- if(strcasecmp($offer['owner_id'], $userID) != 0)
- {
- if(!$offerAux->hasUserAcceptedOffer($userID, $offer['_id']))
- {
- $canAccept = true;
- }
- }
- $ownerDetail = $this->getUserDetails($offer['owner_id']);
- $isCooler = $coolUtility->isCooler($userID,'offer',$offer ["_id"]);
- if($fromWS)
- {
- $isCooler = $isCooler ? 1 : 0;
- }
- $elementOffer = array
- (
- 'classified_id' => $offer['_id'],
- 'title' => $offer["title"],
- 'body' => $offer["description"],
- 'view_count' => $offer["views_count"],
- 'creation_date' => $offer['creation_date']->sec,
- 'photo_url' => SM_BUCKET.$offer['img_url'],
- 'price' => (int)$offer ["price"],
- 'currency' => $offer ["currency"],
- 'location' => $offer['location']['address'],
- 'latitude' => $offer['location']['lat'],
- 'longitude' => $offer['location']['lon'],
- 'limited' => $offer['limitations']['limited_time_offer'] ? "Yes" : "No",
- 'limit_type' => $offer['limitations']['params']['type'],
- 'limit_data' => empty($offer['limitations']['params']['expiration_date']) ? null : $offer['limitations']['params']['expiration_date']->sec,
- 'qr_details' => 'https://'.$_SERVER['HTTP_HOST']."/".$offer['owner_id']."/".$offer['_id'],
- 'participant_counter' => $offer['acceptors_count'],
- 'offer_cools' => $offer['cools_count'],
- 'user_cool' => $isCooler,
- 'can_accept' => $canAccept,
- 'image_orientation' => $offer['img_orientation'],
- 'expired' => $expired,
- 'comment_counter' => $offer['comments_count']
- );
- return array(
- 'offer' => $elementOffer,
- 'owner' => $ownerDetail
- );
- } else {
- return array("error" => "offer was deleted");
- }
- }
- public function acceptOffer($userID, $offerID) {
- $offer = MyMongo_Connection::findOne("offers", array("_id" => $offerID));
- if ($offer == null) {
- $errorArray = array (
- 'error' => 'Offer does not exist'
- );
- return $errorArray;
- }
- if ($offer->closed == true){
- $errorArray = array (
- 'error' => 'Offer is closed'
- );
- return $errorArray;
- }
- if($offer->owner_id === $userID) {
- $errorArray = array (
- 'error' => 'You are owner of the offer, you cannot accept the offer'
- );
- return $errorArray;
- }
- $dateValue = isset($offer->limitations['params']['expiration_date']) ? $offer->limitations['params']['expiration_date']->sec : null;
- if ($dateValue != null) {
- $today = strtotime(date('Y-m-d'));
- $diff = $dateValue - $today;
- $daysleft = round((($diff/24)/60)/60);
- if ($daysleft < 0){
- $errorArray = array (
- 'error' => 'Offer expired'
- );
- return $errorArray;
- }
- }
- $accepted = MyMongo_Connection::count("offers_accepted", array("offer_id" => $offerID, "acceptor_id" => $userID));
- if ($accepted > 0) {
- $errorArray = array (
- 'error' => 'User has already accepted the offer'
- );
- return $errorArray;
- }
- $acceptedArr = array (
- 'offer_id' => $offerID,
- 'acceptor_id' => $userID,
- 'accepted_date' => new MongoDate()
- );
- //aggiorno il contatore di acceptors
- MyMongo_Connection::updateAndOrIncCollectionFields(static::$offersColl, array('_id' => $offerID), array(), array('acceptors_count' => 1));
- MyMongo_Connection::addDocument("offers_accepted", $acceptedArr);
- return array (
- 'Response' => 'Request OK'
- );
- }
- public function getLocations($userID) {
- $photoUtility = Engine_Api::_()->getApi('photoutility', 'core');
- $photos = MyMongo_Connection::find("photos", array("owner_id" => $userID));
- $i = 0;
- foreach ($photos as $photoElement) {
- $arrayCities = $photoUtility->getPhotoCities($photoElement);
- $uploadCity = $arrayCities[0]["city"];
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $photoURLCompleted = SM_BUCKET . $photoElement['thumb_img']['url'];
- $qrDetails = 'https://'.$_SERVER['HTTP_HOST'] . $appName . "user/photodetail/view?p=".$photoElement["_id"];
- $coordinates = $photoUtility->getCoordinates($photoElement);
- if ($coordinates != null) {
- if ($photoElement["deleted"] == false) {
- $arrayLocations [$i] = array (
- 'photo_id' => $photoElement["_id"],
- 'description' => $photoElement ["title"],
- 'upload_city' => $uploadCity,
- 'coordinates' => $coordinates,
- 'photo_url' => $photoURLCompleted,
- 'qr_details' => $qrDetails,
- 'photo_pins' => $photoUtility->getPhotoPins($photoElement),
- 'photo_see' => $photoElement["photosee_count"],
- 'photo_miles' => $photoElement["distance"]
- );
- $i ++;
- }
- }
- }
- $userDetails = $this->getUserDetails($userID);
- return array ('locations' => $arrayLocations, 'owner' => $userDetails);
- }
- /**
- * retrieve all user's Cool notifications
- * @param $userID
- */
- public function getCoolNotification ( $userID ){
- $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
- $select = new Zend_Db_Select($notificationsTable->getAdapter());
- $select->from(array('n' => $notificationsTable->info('name')),
- array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser'))
- ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
- ->where('n.read = 0')
- ->where('n.user_id = ?',$userID)
- ->where('n.type = "liked"');
- $data = $notificationsTable->getAdapter()->fetchAll($select);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note){
- $user = Engine_Api::_()->getDbtable('users', 'user')
- ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
- if ($user->photo_id > 0) {
- $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
- } else {
- $photoProfileUrl = "";
- }
- $userType = $userUtility->getUserType($user->user_id);
- $params = json_decode($note['paramsNot']);
- if (strcasecmp($userType,"personal") == 0){
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'user_id' => $note["subjectUser"],
- 'display_name' => $user["displayname"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'gender' => $userUtility->getUserGender ( $user->user_id ),
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],
- 'object_id' => $note["object_id"],
- 'label' => $params->{'label'}
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'user_id' => $note["subjectUser"],
- 'display_name' => $user["displayname"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],
- 'object_id' => $note["object_id"],
- 'label' => $params->{'label'}
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- $n = $notificationsTable->update (
- array ('read' => 1 ),
- array ('notification_id = ?' => $note["notification_id"])
- );
- }
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's Comments notifications
- * @param $userID
- */
- public function getCommentNotification ( $userID ){
- $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
- $select = new Zend_Db_Select($notificationsTable->getAdapter());
- $select->from(array('n' => $notificationsTable->info('name')),
- array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser','n.type AS notType'))
- ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
- ->where('n.read = 0')
- ->where('n.user_id = ?',$userID)
- ->where('n.type = "commented" OR n.type = "commented_commented"');
- $data = $notificationsTable->getAdapter()->fetchAll($select);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note){
- $user = Engine_Api::_()->getDbtable('users', 'user')
- ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
- $params = json_decode($note['paramsNot']);
- if ($user->photo_id > 0) {
- $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
- } else {
- $photoProfileUrl = "";
- }
- $userType = $userUtility->getUserType($user->user_id);
- if (strcasecmp($userType,"personal") == 0){
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], //tipo notifica commented o commented_commented
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'gender' => $userUtility->getUserGender ( $user->user_id ),
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho commentato album_photo di action
- 'object_id' => $note["object_id"],//id della foto nel caso
- 'label' => $params->{'label'}
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], //tipo notifica commented o commented_commented
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho commentato album_photo di action
- 'object_id' => $note["object_id"],//id della foto nel caso
- 'label' => $params->{'label'}
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- $n = $notificationsTable->update (
- array ('read' => 1 ),
- array ('notification_id = ?' => $note["notification_id"])
- );
- }
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's Photosee notifications
- * @param $userID
- */
- public function getPhotoseeNotification( $userID ){
- $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
- $select = new Zend_Db_Select($notificationsTable->getAdapter());
- $select->from(array('n' => $notificationsTable->info('name')),
- array('n.notification_id','n.user_id','n.subject_id AS subjectUser','n.type AS notType'))
- ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
- ->where('n.read = 0')
- ->where('n.user_id = ?',$userID)
- ->where('n.type = "photo_seen" OR n.type = "photo_seen_seen"');
- $data = $notificationsTable->getAdapter()->fetchAll($select);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note){
- $user = Engine_Api::_()->getDbtable('users', 'user')
- ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
- if ($user->photo_id > 0) {
- $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
- } else {
- $photoProfileUrl = "";
- }
- $userType = $userUtility->getUserType($user->user_id);
- if (strcasecmp($userType,"personal") == 0){
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], // tipo notifica tra photo_seen e photo_seen_seen
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'gender' => $userUtility->getUserGender($user->user_id),
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho photosee album_photo di action
- 'object_id' => $note["object_id"]//id della foto nel caso
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], // tipo notifica tra photo_seen e photo_seen_seen
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho photosee album_photo di action
- 'object_id' => $note["object_id"]//id della foto nel caso
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- $n = $notificationsTable->update (
- array ('read' => 1 ),
- array ('notification_id = ?' => $note["notification_id"])
- );
- }
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's Messages notifications
- * @param $userID
- */
- public function getMessagesNotification($userID, $numOfNotifications, $numOfReceived) {
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $where = array(
- "user_id" => $userID,
- "type" => "message_new"
- );
- $limit = null;
- $offset = null;
- if (isset($numOfNotifications)) {
- if (isset($numOfReceived)) {
- $limit = $numOfNotifications;
- $offset = $numOfReceived;
- } else {
- $limit = $numOfNotifications;
- $offset = 0;
- }
- } else {
- $where["mitigated"] = false;
- }
- $order = array("date" => -1);
- $data = MyMongo_Connection::find("notifications", $where, array(), $order, $limit, $offset);
- $i = 0;
- $toFlagAsRead = array();
- $notificationsArray = array();
- foreach ($data as $note) {
- $user = MyMongo_Connection::findOne("users", array("_id" => $note["subject_id"]));
- if (isset($user->cropped_profilephoto_url)) {
- $photoProfileUrl = SM_BUCKET . $user->cropped_profilephoto_url;
- } else {
- $photoProfileUrl = "";
- }
- $userType = ucfirst($user->type);
- if (strcasecmp($userType,"personal") == 0) {
- $dataEntry = array(
- 'notification_id' => $note["_id"],
- 'notification_type' => $note["type"],
- 'read' => $note["read"] == true ? 1 : 0,
- 'mitigated' => $note["mitigated"] == true ? 1 : 0,
- 'user_id' => $note["subject_id"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'gender' => $user->gender,
- 'user_type' => $userType,
- 'conversation_id' => $note["object_id"],
- 'messages_unread' => $note['params']['unread_msg']
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["_id"],
- 'notification_type' => $note["type"],
- 'read' => $note["read"] == true ? 1 : 0,
- 'mitigated' => $note["mitigated"] == true ? 1 : 0,
- 'user_id' => $note["subject_id"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'user_type' => $userType,
- 'conversation_id' => $note["object_id"],
- 'messages_unread' => $note['params']['unread_msg']
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- if ($note["read"] == false) {
- array_push($toFlagAsRead, $note["_id"]);
- }
- }
- if(sizeof($toFlagAsRead) > 0) {
- MyMongo_Connection::updateCollectionFields("notifications", array("_id" => array('$in' => $toFlagAsRead)), array("read" => true), array("multiple" => true));
- }
- return $notificationsArray;
- }
- /**
- * Resituisce un array che rappresenta un sottoinsieme di follower compresi vari flag (mitigated e read).
- * Inoltre setta le notifiche a lette per ogni elemento restituito dal sottoinsieme.
- * @param $userID
- * @param $numOfNotifications offset
- * @param $numOfReceived limite
- */
- public function getFollowersNotification( $userID,$numOfNotifications,$numOfReceived )
- {
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $followerUserArray = Utilities_Static::getUserutility()->getFollowers($userID, $numOfReceived, $numOfReceived);
- $follower = array();
- $i = 0;
- $notificationIDs = array();
- foreach ( $followerUserArray as $followerUser )
- {
- $alreadyFollowed = "";
- if (Utilities_Static::getUserutility()->isFollowing($userID, $followerUser["_id"]))
- {
- $alreadyFollowed = "true";
- }
- else
- {
- $alreadyFollowed = "false";
- }
- $arrayNoti = Utilities_Static::getUserutility()->getMitigatedFromFollowerNotification($userID, $followerUser['_id']);
- array_push($notificationIDs, $arrayNoti['notification_id']);
- $element = array
- (
- 'user_id' => $followerUser["_id"],
- 'display_name' => Utilities_Static::getUserutility()->getNameOrCompanyOfUser($followerUser),
- 'nickname' => $followerUser['username'],
- 'status' => $followerUser['status'],
- 'photo_profile_url' => Utilities_Static::getProfilePhotoURL($followerUser, true),
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $followerUser['username'],
- 'user_type' => ucfirst($followerUser['type']),
- 'mitigated' => $arrayNoti['mitigated'] ? "1" : "0",
- 'already_followed' => $alreadyFollowed,
- 'notification_id' => $arrayNoti['notification_id'],
- 'notification_type' => 'friend_follow',
- 'read' => $arrayNoti['read'] ? "1" : "0"
- );
- if (strcasecmp ( $followerUser['type'], "personal" ) == 0)
- {
- $element['gender'] = $followerUser['gender'];
- }
- $follower[$i] = $element;
- $i = $i + 1;
- }
- //metto a letto le notifiche elaborate
- MyMongo_Connection::updateCollectionFields
- (
- static::$notificationsColl,
- array('type' => 'friend_follow', '_id' => array('$in' => $notificationIDs)),
- array('read' => true),
- array('multiple' => true)
- );
- return $follower;
- }
- /**
- * this method retrieves all user's Postcard notifications
- * @param $userID
- */
- public function getPostcardNotification($userID, $numOfNotifications, $numOfReceived){
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $where = array(
- "user_id" => $userID,
- "mitigated" => false,
- "type" => "send_postcard"
- );
- $limit = null;
- $offset = null;
- if (isset($numOfNotifications)) {
- if (isset($numOfReceived)) {
- $limit = $numOfNotifications;
- $offset = $numOfReceived;
- } else {
- $limit = $numOfNotifications;
- $offset = 0;
- }
- }
- $order = array("date" => -1);
- $data = MyMongo_Connection::find("notifications", $where, array(), $order, $limit, $offset);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note) {
- $user = MyMongo_Connection::findOne("users", array("_id" => $note["subject_id"]));
- if (isset($user->cropped_profilephoto_url)) {
- $photoProfileUrl = SM_BUCKET . $user->cropped_profilephoto_url;
- } else {
- $photoProfileUrl = "";
- }
- $userType = ucfirst($user->type);
- if (strcasecmp($userType,"personal") == 0) {
- $dataEntry = array(
- 'notification_id' => $note["_id"],
- 'type' => $note["type"],
- 'read' => $note["read"] == true ? 1 : 0,
- 'mitigated' => $note["mitigated"] == true ? 1 : 0,
- 'user_id' => $note["subject_id"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'gender' => $user->gender,
- 'user_type' => $userType,
- 'photo_url' => $note['params']['photo_url']
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["_id"],
- 'type' => $note["type"],
- 'read' => $note["read"] == true ? 1 : 0,
- 'mitigated' => $note["mitigated"] == true ? 1 : 0,
- 'user_id' => $note["subject_id"],
- 'nickname' => $user->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'photo_profile_url' => $photoProfileUrl,
- 'user_type' => $userType,
- 'photo_url' => $note['params']['photo_url']
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- }
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's Photo notifications
- * @param $userID
- */
- public function getPhotoNotification($userID,$numOfNotifications,$numOfReceived)
- {
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $photoTypes = array("photo_moved","liked","commented_mention",
- "commented","commented_commented","photo_seen","photo_seen_seen");
- $limit = $offset = null;
- $condition = array('type' => array('$in' => $photoTypes), 'user_id' => $userID);
- if (isset($numOfNotifications))
- {
- if (isset($numOfReceived))
- {
- $limit = $numOfNotifications;
- $offset = $numOfReceived;
- }
- else
- {
- $limit = $numOfNotifications;
- $offset = 0;
- }
- }
- else
- {
- $condition['read'] = false;
- }
- $data = MyMongo_Connection::find
- (
- static::$notificationsColl,
- $condition,
- array(),
- array('date' => -1),
- $limit,
- $offset
- );
- $i = 0;
- $notificationsArray = array();
- $notIDs = array();
- $activityUtility = Engine_Api::_()->getApi("activityutility","activity");
- foreach ($data as $note)
- {
- $oldTypes = $activityUtility->getOldTypesName($note["object_type"]);
- $userObject = Utilities_Static::getUserutility()->getUser($note['subject_id']);
- $dataEntry = array(
- 'notification_id' => $note["_id"],
- 'type' => $note['type'],
- 'read' => $note["read"] ? 1 : 0,
- 'mitigated' => $note["mitigated"]? 1 : 0,
- 'user_id' => $note["user_id"],
- 'display_name' => Utilities_Static::getUserutility()->getNameOrCompanyOfUser($userObject),
- 'nickname' => $userObject->username,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $userObject->username,
- 'photo_profile_url' => Utilities_Static::getProfilePhotoURL($userObject,true),
- 'user_type' => ucfirst($userObject->type),
- //'action_id' => $note["action_id"],
- 'object_type' => $oldTypes["object_type"],
- 'object_id' => $note["object_id"],
- 'label' => $note['params']['label']
- );
- if( strcasecmp($userObject->type, 'personal') == 0 )
- {
- $dataEntry['gender'] = $userObject->gender;
- }
- $notificationsArray[$i] = $dataEntry;
- $i++;
- array_push($notIDs, $note["_id"]);
- }
- MyMongo_Connection::updateCollectionFields(static::$notificationsColl,array('_id' => array('$in' => $notIDs)), array('read' => true));
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's commented-mention notifications
- * @param $userID
- */
- public function getCommentedMentionNotification( $userID ){
- $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
- $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $select = new Zend_Db_Select($notificationsTable->getAdapter());
- $select->from(array('n' => $notificationsTable->info('name')),
- array('n.notification_id','n.user_id','n.params AS paramsNot','n.subject_id AS subjectUser','n.type AS notType'))
- ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
- ->where('n.read = 0')
- ->where('n.user_id = ?',$userID)
- ->where('n.type = "commented_mention" ')
- ->order('n.date DESC');
- $data = $notificationsTable->getAdapter()->fetchAll($select);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note){
- $user = Engine_Api::_()->getDbtable('users', 'user')
- ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
- $params = json_decode($note['paramsNot']);
- if ($user->photo_id > 0) {
- $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
- } else {
- $photoProfileUrl = "";
- }
- $userType = $userUtility->getUserType($user->user_id);
- if (strcasecmp($userType,"personal") == 0){
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"],
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'gender' => $userUtility->getUserGender($user->user_id),
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho mention album_photo di action
- 'object_id' => $note["object_id"],//id della foto nel caso
- 'label' => $params->{'label'}
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"],
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti su cui ho mention album_photo di action
- 'object_id' => $note["object_id"],//id della foto nel caso
- 'label' => $params->{'label'}
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- $n = $notificationsTable->update (
- array ('read' => 1 ),
- array ('notification_id = ?' => $note["notification_id"])
- );
- }
- return $notificationsArray;
- }
- /**
- * this method retrieves all user's Photosee notifications
- * @param $userID
- */
- public function getAllNotification( $userID ){
- $notificationsTable = Engine_Api::_()->getDbTable('notifications','activity');
- $userUtility = Engine_Api::_()->getApi('userutility','core');
- $appName = Zend_Registry::get('Zend_View')->baseUrl() . "/";
- $filesTable = Engine_Api::_()->getDbtable('files', 'storage');
- $actionsTable = Engine_Api::_()->getDbTable('actions','activity');
- $select = new Zend_Db_Select($notificationsTable->getAdapter());
- $select->from(array('n' => $notificationsTable->info('name')),
- array('n.notification_id','n.user_id','n.subject_id AS subjectUser','n.type AS notType'))
- ->join(array('a' => $actionsTable->info('name')), 'n.object_id = a.action_id')
- ->where('n.read = 0')
- ->where('n.user_id = ?',$userID)
- ->where('n.type = "photo_seen" OR n.type = "photo_seen_seen" OR n.type = "commented" OR
- n.type = "commented_commented" OR n.type = "commented_mention OR
- n.type = "message_new" OR n.type = "friend_follow" OR n.type = "liked" ');
- $data = $notificationsTable->getAdapter()->fetchAll($select);
- $i = 0;
- $notificationsArray = array();
- foreach ($data as $note){
- $user = Engine_Api::_()->getDbtable('users', 'user')
- ->fetchRow(array('user_id = ?' => $note["subjectUser"]));
- if ($user->photo_id > 0) {
- $photoProfileUrl = $filesTable->getFile ( $user->photo_id, 'thumb.profile' )->map ();
- } else {
- $photoProfileUrl = "";
- }
- $userType = $userUtility->getUserType($user->user_id);
- if (strcasecmp($userType,"personal") == 0){
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], // tipo notifica
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'gender' => $userUtility->getUserGender($user->user_id),
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti
- 'object_id' => $note["object_id"]//id dell'oggetto di riferimento
- );
- } else {
- $dataEntry = array(
- 'notification_id' => $note["notification_id"],
- 'notification_type' => $note["notType"], // tipo notifica
- 'user_id' => $note["subjectUser"],//mia notifica
- 'display_name' => $user["displayname"],
- 'nickname' => $user["username"],
- 'photo_profile_url' => $photoProfileUrl,
- 'qr_details' => 'https://' . $_SERVER ['HTTP_HOST'] . $appName . "profile/" . $user->username,
- 'user_type' => $userType,
- 'action_id' => $note["action_id"],
- 'object_type' => $note["object_type"],//tipo di oggetti
- 'object_id' => $note["object_id"]//id dell'oggetto di riferimento
- );
- }
- $notificationsArray[$i] = $dataEntry;
- $i = $i + 1;
- $n = $notificationsTable->update (
- array ('read' => 1 ),
- array ('notification_id = ?' => $note["notification_id"])
- );
- }
- return $notificationsArray;
- }
- /**
- * This method allows user delete from SMPN
- */
- public function deleteUser($userID, $motivationID, $device_id)
- {
- $deleteRequest = MyMongo_Connection::findOne('core_pendingdeleterequests', array('user_id' => $userID));
- if (!is_null($deleteRequest))
- {
- $errorArray = array (
- 'error' => 'Delete request already done'
- );
- return $errorArray;
- }
- else
- {
- Engine_Api::_()->user()->removeSocialmaticUser(MyMongo_Connection::findOne(static::$usersCollection,array('_id' => $userID)), $motivationID);
- return array (
- 'Response' => 'Request OK'
- );
- }
- }
- /**
- * This method returns all of my past events
- * @param $userID
- */
- public function getPastEvents ( $userID )
- {
- $eventAuxiliary = Engine_Api::_ ()->getApi ( 'eventauxiliary', 'event' );
- $eventsPast = $eventAuxiliary->getEventsByUserID($userID,null,null,false,false);
- $arrayEvents = $this->buildEventsList($eventsPast);
- Utilities_Static::getUserutility()->resetNotificationTypeForUser($userID, "event_create");
- return $arrayEvents;
- }
- /**
- * This method returns all of my events
- * @param $userID
- */
- public function getMyEvents ( $userID )
- {
- $eventAuxiliary = Engine_Api::_ ()->getApi ( 'eventauxiliary', 'event' );
- $myEvents = $eventAuxiliary->getEventsByUserID($userID,null,null,null,true);
- $arrayEvents = $this->buildEventsList($myEvents);
- return $arrayEvents;
- }
- private function buildEventsList($eventsList)
- {
- $arrayEvents = array();
- $i = 0;
- foreach ( $eventsList as $event )
- {
- $startTime = $event["start_time"]->sec;
- $user = $this->getUserDetails ( $event ["owner_id"] );
- $elementEvents = array (
- 'event_id' => $event ["_id"],
- 'title' => $event ["title"],
- 'description' => $event ["description"],
- 'starttime' => $startTime,
- 'photo_url' => SM_BUCKET.$event['img_url'],
- 'member_count' => $event ["attenders_count"],
- 'image_orientation' => $event['img_orientation']
- );
- $arrayEvents [$i] = array (
- "event" => $elementEvents,
- "owner" => $user
- );
- $i ++;
- }
- return $arrayEvents;
- }
- public function getMyOffers($userID) {
- $user = Engine_Api::_()->user()->getUser($userID);
- $userDetails = $this->buildUserArr((array)$user);
- $offers = MyMongo_Connection::find("offers", array("owner_id" => $userID), array(), array('creation_date' => -1));
- $arrayOffers = array();
- $i = 0;
- foreach($offers as $offer) {
- $limitedValue = "No";
- $limitData = isset($offer['limitations']['params']['expiration_date']) ? $offer['limitations']['params']['expiration_date']->sec : null;
- $limitTypeValue = isset($offer['limitations']['params']['type']) ? $offer['limitations']['params']['type'] : null;
- if($limitTypeValue != null) {
- $limitedValue = "Yes";
- }
- $startTime = $offer["creation_date"]->sec;
- $dateStart = new Zend_Date($startTime );
- $dateStart->setTimezone($user->timezone);
- $photoURLCompleted = SM_BUCKET . $offer['img_url'];
- $price = $offer['price'];
- $currency = $offer['currency'];
- $location = $offer['location']['address'];
- $qrDetails = Engine_Api::_()->getApi("offerauxiliary","classified")->getOfferHref($offer, true);
- if (isset($limitTypeValue)) {
- if (isset($limitData)) {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'closed' => $offer["closed"],
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'limit_type' => $limitTypeValue,
- 'limit_date' => $limitData,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- } else {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'closed' => $offer["closed"],
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'limit_type' => $limitTypeValue,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- }
- } else {
- $elementOffers = array (
- 'offer_id' => $offer ["_id"],
- 'title' => $offer ["title"],
- 'body' => $offer ["description"],
- 'creation_date' => $startTime,
- 'photo_url' => $photoURLCompleted,
- 'closed' => $offer["closed"],
- 'price' => $price,
- 'currency' => $currency,
- 'location' => $location,
- 'limited' => $limitedValue,
- 'qr_details' => $qrDetails,
- 'image_orientation' => $offer["img_orientation"]
- );
- }
- $arrayOffers [$i] = array(
- 'offer' => $elementOffers,
- 'owner' => $userDetails
- );
- $i++;
- }
- return $arrayOffers;
- }
- /**
- * this function post a new offer
- */
- public function postOffer( $userID, $offerParameters)
- {
- $parameterArrays = Zend_Json_Decoder::decode ( $offerParameters, true ); // decode JSON to associative array
- if (! array_key_exists("offer_title",$parameterArrays[0])){
- return array (
- "error",
- "offer_title parameter must be setted"
- );
- }
- if (! array_key_exists("offer_type",$parameterArrays[0])){
- return array (
- "error",
- "offer_type parameter must be setted"
- );
- }
- if (! array_key_exists("description",$parameterArrays[0])){
- return array (
- "error",
- "description parameter must be setted"
- );
- }
- if (! array_key_exists("price",$parameterArrays[0])){
- return array (
- "error",
- "price parameter must be setted"
- );
- }
- if (! array_key_exists("currency",$parameterArrays[0])){
- return array (
- "error",
- "currency parameter must be setted"
- );
- }
- if (! array_key_exists("location",$parameterArrays[0])){
- return array (
- "error",
- "location parameter must be setted"
- );
- }
- if (! array_key_exists("limited_time_offer",$parameterArrays[0])){
- return array (
- "error",
- "limited_time_offer parameter must be setted"
- );
- }
- if (MyMongo_Connection::count(static::$offersCategoriesCollection, array('_id' => (int)$parameterArrays[0]["offer_type"])) == 0)
- {
- return array (
- "error",
- "value of offer_type is not allowed"
- );
- }
- if (! is_numeric($parameterArrays[0]["price"]))
- {
- return array (
- "error",
- "value of price must be numeric"
- );
- }
- $currency = MyMongo_Connection::findOne(static::$offerCurrenciesCollection, array('_id' => (int)$parameterArrays[0]["currency"]));
- if (is_null($currency))
- {
- return array (
- "error",
- "currency value is not allowed"
- );
- }
- $currency = $currency->currency;
- $isLimited = $parameterArrays[0]["limited_time_offer"]; //Yes oppure No
- //se non è né yes né no
- if(strcasecmp($isLimited, "yes") != 0 && strcasecmp($isLimited, "no") != 0)
- {
- return array (
- "error",
- "limited_time_offer value is not allowed"
- );
- }
- $limitationTypeOffer = null;
- //se l'offerta è limitata
- if(strcasecmp($isLimited, "yes") == 0)
- {
- //se non è specificata la tipologia
- if ((!array_key_exists("limitation_type",$parameterArrays[0])))
- { return array
- (
- "error",
- "if limited_time_offer value is Yes, limitation_type must be setted"
- );
- }
- $expirationTypeDoc = MyMongo_Connection::findOne(static::$offerLimitationTypes,array('_id' => (int)$parameterArrays[0]["limitation_type"]));
- $limitationTypeOffer = $expirationTypeDoc->type;
- //se è di tipo expires on e non ha una data di scadenza
- if (strcasecmp($limitationTypeOffer,"Expires on") == 0 && !array_key_exists("expiration_date",$parameterArrays[0]))
- {
- return array
- (
- "error",
- "if limitation_type value is 'expires on', expiration_date must be setted"
- );
- }
- //se è While stocks last
- if(strcasecmp($limitationTypeOffer,"While stocks last") == 0 && array_key_exists('expiration_date', $parameterArrays[0]))
- {
- return array (
- "error",
- "if limitation_type value is 'while stocks last', expiration_date parameter is not allowed"
- );
- }
- //se è di tipo expires on
- if(strcasecmp($limitationTypeOffer,"Expires on") == 0)
- {
- // value string must be in the form of yyyy-mm-dd
- $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd'));
- if (!$validator->isValid( $parameterArrays[0]["expiration_date"] ))
- {
- return array (
- "error",
- "expiration_date must be in format 'yyyy-mm-dd'"
- );
- }
- $date = strtotime($parameterArrays[0]["expiration_date"]);
- if ($date < time()-24*60*60)
- {
- return array (
- "error",
- "expiration_date is in the past"
- );
- }
- }
- }
- //se l'offerta non è limitata
- else
- {
- //se non è limitata non devono essere specificati parametri
- if((array_key_exists("limitation_type",$parameterArrays[0])))
- {
- return array (
- "error",
- "if limited_time_offer value is No, limitation_type parameter is not allowed"
- );
- }
- }
- if (!array_key_exists("photo_id",$parameterArrays[0]) && !array_key_exists("photo_base64",$parameterArrays[0]))
- {
- return array (
- "error",
- "photo_id or the photo_base64 must be provided"
- );
- }
- if (array_key_exists("photo_id",$parameterArrays[0]) && array_key_exists("photo_base64",$parameterArrays[0]))
- { return array (
- "error",
- "photo_id or the photo_base64 must be provided not both"
- );
- }
- $photoURL = "";
- $orientation = "";
- if (array_key_exists("photo_id", $parameterArrays[0]))
- {
- $photoId = $parameterArrays[0]["photo_id"];
- $photo = MyMongo_Connection::findOne(static::$photosColl, array('_id'=>$photoId, 'owner_id' => $userID));
- if (is_null($photo))
- {
- return array (
- "error",
- "photo_id value is not allowed or you aren't owner of photo"
- );
- }
- else
- {
- $photoURL = $photo->fullsize_img['url'];
- $orientation = $photo->img_orientation;
- }
- }
- elseif (array_key_exists("photo_base64",$parameterArrays[0]))
- {
- if ((array_key_exists("photo_base64",$parameterArrays[0])) && (!array_key_exists("crop_coord",$parameterArrays[0])))
- {
- return array (
- "error",
- "crop_coord must be setted"
- );
- }
- else
- {
- $coords = explode(":",$parameterArrays[0]['crop_coord']);
- $orientation = 'horizontal';
- if((int)$coords[2] < (int)$coords[3])
- {
- $orientation = 'vertical';
- }
- $photoURL = Engine_Api::_()->getApi("offerauxiliary","classified")->saveCustomOfferImage($userID, str_replace(" ", "+", $parameterArrays[0]['photo_base64']), $coords, $orientation, false, true);
- }
- }
- $creation_date = new MongoDate();
- $_id = hash("md5",$userID . $creation_date->__toString());
- $cat = MyMongo_Connection::findOne(static::$offersCategoriesCollection, array('_id' => (int)$parameterArrays[0]["offer_type"]));
- $cat = $cat->type;
- //ottengo coordinate dal nome della località
- $coordinates = $this->get_lat_long($parameterArrays[0]['location']);
- $limitationsArray = array('limited_time_offer' => false);
- //se l'offerta ha delle limitazioni
- if(strcasecmp($isLimited, "yes") == 0)
- {
- $limitationsArray = array('limited_time_offer' => true);
- //se ha una limitazione di tipo scadenza (expires on)
- if(strcasecmp($limitationTypeOffer, "Expires on") == 0)
- {
- $expirationTime = $date;
- $limitationsArray['params'] = array(
- 'type' => "Expires on",
- 'expiration_date' => new MongoDate($expirationTime)
- );
- }
- else
- {
- $limitationsArray['params'] = array('type' => "While stocks last");
- }
- }
- // deviceID=9C65F910-6EF8-4340-2121-054520480426-5814&authtoken=E5E6FAB6-ACDF513F-759E8098-3F11CDCA&userID=5c5b7e654a126750dab7a83cf6b3c85a&offerParameters=[{"offer_title":"Offerta test","offer_type":"1","description":"Descrizione offerta","price":"1","currency":"2","location":"Benevento","limited_time_offer":"No","photo_id":"4cd8028b76a490ef839b7a22b18db50b"}]
- //aggiungo l'offerta nel db
- MyMongo_Connection::addDocument(static::$offersColl,
- array
- (
- '_id' => $_id,
- 'title' => $parameterArrays[0]['offer_title'],
- 'description' => $parameterArrays[0]['description'],
- 'owner_id' => $userID,
- 'category' => $cat,
- 'creation_date' => $creation_date,
- 'modified_date' => $creation_date,
- 'views_count' => 0,
- 'comments_count' => 0,
- 'closed' => false,
- 'img_url' => $photoURL,
- 'img_orientation' => $orientation,
- 'acceptors_count' => 0,
- 'cools_count' => 0,
- 'price' => (int)$parameterArrays[0]['price'],
- 'currency' => $currency,
- 'location' => array('address' => $parameterArrays[0]['location'], 'lat' => $coordinates['lat'], 'lon' => $coordinates['lon']),
- 'limitations' => $limitationsArray
- )
- );
- $now = $creation_date;
- /*metto in coda per le notifiche l'offerta appena creata (usercreationdate_offset viene usato come offset, ovvero ogni volta che scatta il task sarò inviata la
- notifica a tutti coloro che si sono iscritti in precedenza a questa data).
- */
- MyMongo_Connection::addDocument(static::$offersTaskColl, array(
- 'offer_id' => $_id,
- 'owner_id' => $userID,
- 'taskcreation_date' => $now,
- 'usercreationdate_offset' => $now,
- 'active' => true,
- 'type' => 'offer',
- 'title' => $parameterArrays[0]['offer_title'],
- 'photo_url' => SM_BUCKET.$photoURL,
- 'photo_orientation' => $orientation,
- 'price' => floatval(str_replace(",", ".", $parameterArrays[0]['price'])),
- 'currency' => $currency,
- 'location' => array('address' => $parameterArrays[0]['location'], 'lat' => $coordinates['lat'], 'lon' => $coordinates['lon']),
- 'limited' => ucfirst($isLimited)
- ));
- $flowItem = array('item_id'=>$_id,'item_type'=>'offer','poster_id'=>$userID,'post_date'=>$now);
- //aggiungo nel flow del poster
- //MyMongo_Connection::addInArrayInDocument(static::$feedsColl, array('_id' => $userID), 'posts', $flowItem);
- MyMongo_Connection::addInFeed($userID, array($flowItem), 128);
- //aggiungo il post nella collection generale dei post
- MyMongo_Connection::addDocument(static::$postsColl, $flowItem);
- return array('Response' => 'Request OK', 'offer' =>
- array(
- 'offer_id' => $_id,
- 'photo_url' => SM_BUCKET.$photoURL,
- 'photo_orientation' => $orientation,
- 'creation_date' => $now->sec,
- 'limited' => ucfirst($isLimited),
- 'currency' => $currency,
- 'limit_type' => $limitationsArray
- ));
- }
- public function postEvent($userID, $eventParameters) {
- $eventParams = array();
- $parameterArrays = Zend_Json_Decoder::decode($eventParameters, true); // decode JSON to associative array
- $eventParams['owner_id'] = $userID;
- if (! array_key_exists("title", $parameterArrays[0])) {
- return array(
- "error",
- "title parameter must be setted"
- );
- } else {
- $eventParams["title"] = $parameterArrays[0]["title"];
- }
- if (! array_key_exists("description",$parameterArrays[0])) {
- return array(
- "error",
- "description parameter must be setted"
- );
- } else {
- $eventParams["description"] = $parameterArrays[0]["description"];
- }
- if (! array_key_exists("starttime",$parameterArrays[0])) {
- return array (
- "error",
- "starttime parameter must be setted"
- );
- }
- if (! array_key_exists("endtime",$parameterArrays[0])) {
- return array (
- "error",
- "endtime parameter must be setted"
- );
- }
- if (! array_key_exists("location",$parameterArrays[0])) {
- return array (
- "error",
- "location parameter must be setted"
- );
- }
- else
- {
- if(Utilities_Static::getTextUtility()->isThereEmoji($parameterArrays[0]["location"]))
- {
- return array("error","location is not valid");
- }
- else
- {
- $eventParams["location"] = $parameterArrays[0]["location"];
- }
- }
- if (! array_key_exists("category_id",$parameterArrays[0])) {
- return array (
- "error",
- "category_id parameter must be setted"
- );
- }
- $category = MyMongo_Connection::findOne("event_categories", array("category_id" => (int)$parameterArrays[0]["category_id"]));
- if ($category == null) {
- return array (
- "error",
- "category_id value not allowed"
- );
- } else {
- $eventParams['category'] = $category->title;
- }
- $startstring = str_replace(" "," +",$parameterArrays[0]["starttime"]);
- $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd H:i:s '));
- if ((!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) ([+-](2[0-3]|[0-1][0-9]):([0-5][0-9]))$/", $startstring)) || (!$validator->isValid($startstring))) {
- return array (
- "error",
- "starttime must be in format 'yyyy-mm-dd H:i:s [+|-]xx:zz'"
- );
- }
- $start = new DateTime($startstring);
- $oldTz = date_default_timezone_get();
- date_default_timezone_set($start->getTimezone()->getName());
- $starttime = strtotime($startstring);
- date_default_timezone_set($oldTz);
- $endstring = str_replace(" "," +",$parameterArrays[0]["endtime"]);
- $validator = new Zend_Validate_Date(array('format'=>'yyyy-MM-dd H:i:s '));
- if ((!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) ([+-](2[0-3]|[0-1][0-9]):([0-5][0-9]))$/", $endstring)) || (!$validator->isValid($endstring))) {
- return array (
- "error",
- "endtime must be in format 'yyyy-mm-dd H:i:s [+|-]xx:zz'"
- );
- }
- $end = new DateTime($endstring);
- date_default_timezone_set($end->getTimezone()->getName());
- $endtime = strtotime($endstring);
- date_default_timezone_set($oldTz);
- if ($endtime < $starttime) {
- return array (
- "error",
- "endtime is before of starttime"
- );
- }
- if ($starttime < time()) {
- return array (
- "error",
- "starttime is in the past"
- );
- }
- if ($endtime < time()) {
- return array (
- "error",
- "endtime is in the past"
- );
- }
- // ----------------------------------------------
- // Handling event's photo
- if (!array_key_exists("photo_id", $parameterArrays[0]) && !array_key_exists("photo_base64", $parameterArrays[0])) {
- return array (
- "error",
- "photo_id or the photo_base64 must be provided"
- );
- }
- if (array_key_exists("photo_id", $parameterArrays[0]) && array_key_exists("photo_base64", $parameterArrays[0])) {
- return array (
- "error",
- "photo_id or the photo_base64 must be provided not both"
- );
- }
- if (array_key_exists("photo_id", $parameterArrays[0])) {
- $photo = MyMongo_Connection::findOne("photos", array("_id" => $parameterArrays[0]["photo_id"], "owner_id" => $userID));
- if ($photo == null) {
- return array (
- "error",
- "photo_id value is not allowed or you aren't owner of photo"
- );
- }
- $eventParams['localPhotoUpload'] = false;
- $eventParams['base64OrURL'] = $photo->fullsize_img['url'];
- $eventParams['photoOrientation'] = $photo->img_orientation;
- } elseif(array_key_exists("photo_base64", $parameterArrays[0])) {
- if ((array_key_exists("photo_base64", $parameterArrays[0])) && (!array_key_exists("crop_coord", $parameterArrays[0]))) {
- return array (
- "error",
- "crop_coord must be setted"
- );
- }
- $coord = explode ( ":", $parameterArrays [0] ["crop_coord"] );
- if (intval ( $coord [2] ) > intval ( $coord [3] )) {
- $eventParams['photoOrientation'] = "horizontal";
- } else {
- $eventParams['photoOrientation'] = "vertical";
- }
- $coord [2] = intval ( $coord [0] ) + intval ( $coord [2] );
- $coord [3] = intval ( $coord [1] ) + intval ( $coord [3] );
- if (strcasecmp ( $parameterArrays [0] ["photo_base64"], "" ) != 0) {
- $eventParams['cropCoordinates'] = implode(";", $coord);
- $eventParams['localPhotoUpload'] = true;
- $eventParams['base64OrURL'] = str_replace(" ", "+", $parameterArrays[0]["photo_base64"]);
- } else {
- return array (
- "error",
- "photo_base64 value can not be empty"
- );
- }
- }
- //----------------------------------------------
- $user = MyMongo_Connection::findOne("users", array("_id" => $userID));
- $start_date = new Zend_Date(date("m/d/Y H:i", $starttime), Zend_Date::DATETIME_FULL, $user->locale);
- $end_date = new Zend_Date(date("m/d/Y H:i", $endtime), Zend_Date::DATETIME_FULL, $user->locale);
- // Create event
- $eventAuxiliary = Engine_Api::_()->getApi('eventauxiliary', 'event');
- $response = $eventAuxiliary->createEvent($eventParams, $start_date, $end_date, (array)$user, true);
- return array('Response' => 'Request OK', 'event' =>
- array
- (
- 'event_id' => $response['messages']['eventID'],
- 'photo_url' => $response['messages']['photo_url'],
- 'photo_orientation' => $response['messages']['photo_orientation'],
- 'starttime' => $response['messages']['starttime'],
- 'endtime' => $response['messages']['endtime']
- )
- );
- }
- /**
- * In base alla versione passata in input, questo metodo restituisce il firmware aggiornato o un
- * messaggio che indica che la versione passata è già aggiornata (o che non ci sono aggiornamenti).
- * @param $version array con due campi status (0 no aggiornamenti, 1 aggiornamenti) e content (messaggio se status è 0
- * oppure firmware in base64 se status vale 1)
- * @return
- */
- public function getFirmwareUpdates($version) {
- $firmware = MyMongo_Connection::findOne("core_printingfirmware", array("_id" => array('$exists' => true)));
- $response = array(
- "status" => 0,
- "content" => "No updates available",
- );
- if($firmware != null) {
- //if the user has an older version
- if(intval($firmware->version) > intval($version)) {
- $response = array(
- "status" => 1,
- "content" => $firmware->content,
- "md5checksum" => $firmware->md5checksum
- );
- }
- }
- return $response;
- }
- /**
- * Verifica l'esistenza di una certa risorsa di un certo tipo
- * @param $objectID id della risorsa
- * @param $objectType tipologia della risorsa
- */
- public function checkObjectExistence ($objectID, $objectType)
- {
- $collection = "";
- //album_photo, classified, event ----> valori assumibili da objectType
- if(strcasecmp($objectType, "album_photo") == 0)
- {
- $collection = 'photos';
- }
- else if(strcasecmp($objectType, "classified") == 0)
- {
- $collection = 'offers';
- }
- else if(strcasecmp($objectType, "event") == 0)
- {
- $collection = 'events';
- }
- else
- {
- return false;
- }
- if(strcasecmp($objectType, "album_photo") == 0) {
- return MyMongo_Connection::count($collection, array('_id' => $objectID, "deleted" => false)) > 0;
- } else {
- return MyMongo_Connection::count($collection, array('_id' => $objectID)) > 0;
- }
- }
- }
Add Comment
Please, Sign In to add comment